Uri   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 16
c 2
b 0
f 0
dl 0
loc 41
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 7 2
A __construct() 0 24 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource;
6
7
use BEAR\Resource\Exception\UriException;
8
9
use function array_key_exists;
10
use function count;
11
use function filter_var;
12
use function parse_str;
13
use function parse_url;
14
use function sprintf;
15
use function uri_template;
16
17
use const FILTER_FLAG_PATH_REQUIRED;
18
use const FILTER_VALIDATE_URL;
19
20
final class Uri extends AbstractUri
21
{
22
    /**
23
     * @param array<string, mixed> $query
24
     *
25
     * @throws UriException
26
     */
27
    public function __construct(
28
        string $uri,
29
        array $query = [],
30
    ) {
31
        $this->validate($uri);
32
        if (count($query) !== 0) {
33
            $uri = uri_template($uri, $query);
34
        }
35
36
        $parts = (array) parse_url($uri);
37
        $host = isset($parts['port']) ? sprintf('%s:%s', $parts['host'] ?? '', $parts['port'] ?? '') : $parts['host'] ?? ''; // @phpstan-ignore-line
38
        [$this->scheme, $this->host, $this->path] = [$parts['scheme'] ?? '', $host, $parts['path'] ?? ''];
39
        $parseQuery = $this->query;
40
        if (array_key_exists('query', $parts)) {
41
            parse_str($parts['query'], $parseQuery);
42
            /** @var array<string, mixed> $parseQuery */ // phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.NoAssignment
43
            $this->query = $parseQuery;
44
        }
45
46
        if (count($query) === 0) {
47
            return;
48
        }
49
50
        $this->query = $query + $parseQuery;
51
    }
52
53
    /** @throws UriException */
54
    private function validate(string $uri): void
55
    {
56
        if (filter_var($uri, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)) {
57
            return;
58
        }
59
60
        throw new UriException($uri, 500);
61
    }
62
}
63