<?php

namespace Hura8;

class Url
{

    public static function parse($url) {
        $data = parse_url($url);
        $default = [
            'scheme' => '',
            'host' => '',
            'port' => '',
            'user' => '',
            'pass' => '',
            'path' => '',
            'query' => [],
            'fragment' => '',
        ];
        foreach ($data as $key => $value) {
            if(isset($default[$key])) {
                $default[$key] = ($key == 'query') ? self::parsedQuery($value) : $value;
            }
        }

        return $default;
    }


    public static function parsedQuery($query = '') {
        if(!$query) return [];
        $result = [];
        $parts = explode("&", $query);

        foreach ($parts as $part) {
            $el = explode("=", $part);
            if(sizeof($el) != 2) continue;

            $cleaned_key    = preg_replace("/[^a-z0-9_\-\.]/i", '', $el[0]);
            $cleaned_value  = preg_replace("/[^a-z0-9_\.\-;&]/i", '', $el[1]);

            $result[$cleaned_key] = $cleaned_value;
        }

        return $result;
    }
}
