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 | 110 | use function sprintf; |
|
15 | use function uri_template; |
||
16 | 110 | ||
17 | 108 | use const FILTER_FLAG_PATH_REQUIRED; |
|
18 | 2 | use const FILTER_VALIDATE_URL; |
|
19 | |||
20 | 108 | /** @psalm-import-type Query from Types */ |
|
21 | 108 | final class Uri extends AbstractUri |
|
22 | 108 | { |
|
23 | 37 | /** |
|
24 | * @param Query $query |
||
25 | 108 | * |
|
26 | 2 | * @throws UriException |
|
27 | */ |
||
28 | 108 | public function __construct( |
|
29 | string $uri, |
||
30 | array $query = [], |
||
31 | ) { |
||
32 | $this->validate($uri); |
||
33 | 110 | if (count($query) !== 0) { |
|
34 | $uri = uri_template($uri, $query); |
||
35 | 110 | } |
|
36 | 3 | ||
37 | $parts = (array) parse_url($uri); |
||
38 | 3 | $host = isset($parts['port']) ? sprintf('%s:%s', $parts['host'] ?? '', $parts['port'] ?? '') : $parts['host'] ?? ''; // @phpstan-ignore-line |
|
39 | [$this->scheme, $this->host, $this->path] = [$parts['scheme'] ?? '', $host, $parts['path'] ?? '']; |
||
40 | 108 | $parseQuery = $this->query; |
|
41 | if (array_key_exists('query', $parts)) { |
||
42 | parse_str($parts['query'], $parseQuery); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
43 | /** @var Query $parseQuery */ // phpcs:ignore SlevomatCodingStandard.Commenting.InlineDocCommentDeclaration.NoAssignment |
||
44 | $this->query = $parseQuery; |
||
45 | } |
||
46 | |||
47 | if (count($query) === 0) { |
||
48 | return; |
||
49 | } |
||
50 | |||
51 | $this->query = $query + $parseQuery; |
||
52 | } |
||
53 | |||
54 | /** @throws UriException */ |
||
55 | private function validate(string $uri): void |
||
56 | { |
||
57 | if (filter_var($uri, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)) { |
||
58 | return; |
||
59 | } |
||
60 | |||
61 | throw new UriException($uri, 500); |
||
62 | } |
||
63 | } |
||
64 |