Completed
Pull Request — master (#84)
by
unknown
02:04
created

Parser   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 24
c 4
b 0
f 0
dl 0
loc 54
ccs 0
cts 21
cp 0
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A parseUrl() 0 23 5
A doParseUrl() 0 5 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Purl;
6
7
use InvalidArgumentException;
8
9
use function array_merge;
10
use function array_reverse;
11
use function explode;
12
use function implode;
13
use function parse_url;
14
use function sprintf;
15
16
/**
17
 * Parser class.
18
 */
19
class Parser implements ParserInterface
20
{
21
    /** @var mixed[] */
22
    private static array $defaultParts = [
23
        'scheme'             => null,
24
        'host'               => null,
25
        'port'               => null,
26
        'user'               => null,
27
        'pass'               => null,
28
        'path'               => null,
29
        'query'              => null,
30
        'fragment'           => null,
31
        'canonical'          => null,
32
        'resource'           => null,
33
    ];
34
35
    /**
36
     * @param string|Url|null $url
37
     *
38
     * @return mixed[]
39
     */
40
    public function parseUrl($url): array
41
    {
42
        $url = (string) $url;
43
44
        $parsedUrl = $this->doParseUrl($url);
45
46
        if ($parsedUrl === []) {
47
            throw new InvalidArgumentException(sprintf('Invalid url %s', $url));
48
        }
49
50
        $parsedUrl = array_merge(self::$defaultParts, $parsedUrl);
51
52
        if (isset($parsedUrl['host'])) {
53
            $parsedUrl['canonical'] = implode('.', array_reverse(explode('.', $parsedUrl['host']))) . ($parsedUrl['path'] ?? '') . (isset($parsedUrl['query']) ? '?' . $parsedUrl['query'] : '');
54
55
            $parsedUrl['resource'] = $parsedUrl['path'] ?? '';
56
57
            if (isset($parsedUrl['query'])) {
58
                $parsedUrl['resource'] .= '?' . $parsedUrl['query'];
59
            }
60
        }
61
62
        return $parsedUrl;
63
    }
64
65
    /**
66
     * @return mixed[]
67
     */
68
    protected function doParseUrl(string $url): array
69
    {
70
        $parsedUrl = parse_url($url);
71
72
        return $parsedUrl !== false ? $parsedUrl : [];
73
    }
74
}
75