Parser::doParseUrl()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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