1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of Spiral Framework package. |
5
|
|
|
* |
6
|
|
|
* For the full copyright and license information, please view the LICENSE |
7
|
|
|
* file that was distributed with this source code. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
declare(strict_types=1); |
11
|
|
|
|
12
|
|
|
namespace Spiral\Storage\Parser; |
13
|
|
|
|
14
|
|
|
use Psr\Http\Message\UriInterface as PsrUriInterface; |
15
|
|
|
use Spiral\Storage\Exception\UriException; |
16
|
|
|
|
17
|
|
|
final class UriParser implements UriParserInterface |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var string |
21
|
|
|
*/ |
22
|
|
|
private const ERROR_INVALID_URI_TYPE = |
23
|
|
|
'URI argument must be a string-like ' . |
24
|
|
|
'or instance of one of [%s], but %s passed' |
25
|
|
|
; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* {@inheritDoc} |
29
|
|
|
*/ |
30
|
|
|
public function parse($uri): UriInterface |
31
|
|
|
{ |
32
|
|
|
switch (true) { |
33
|
|
|
case $uri instanceof UriInterface: |
34
|
|
|
return $uri; |
35
|
|
|
|
36
|
|
|
case \is_string($uri): |
37
|
|
|
case $uri instanceof \Stringable: |
38
|
|
|
return $this->fromString((string)$uri); |
39
|
|
|
|
40
|
|
|
case $uri instanceof PsrUriInterface: |
41
|
|
|
return $this->fromPsrUri($uri); |
42
|
|
|
|
43
|
|
|
default: |
44
|
|
|
$message = \vsprintf(self::ERROR_INVALID_URI_TYPE, [ |
45
|
|
|
\implode(', ', [UriInterface::class, PsrUriInterface::class]), |
46
|
|
|
\get_debug_type($uri), |
47
|
|
|
]); |
48
|
|
|
|
49
|
|
|
throw new UriException($message); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param PsrUriInterface $uri |
55
|
|
|
* @return UriInterface |
56
|
|
|
* @throws UriException |
57
|
|
|
*/ |
58
|
|
|
private function fromPsrUri(PsrUriInterface $uri): UriInterface |
59
|
|
|
{ |
60
|
|
|
$path = \implode('/', [$uri->getHost(), $uri->getPath()]); |
61
|
|
|
|
62
|
|
|
return new Uri($uri->getScheme(), $path); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param string $uri |
67
|
|
|
* @return UriInterface |
68
|
|
|
* @throws UriException |
69
|
|
|
*/ |
70
|
|
|
private function fromString(string $uri): UriInterface |
71
|
|
|
{ |
72
|
|
|
$chunks = \explode('://', $uri); |
73
|
|
|
|
74
|
|
|
return new Uri(\array_shift($chunks), \implode('/', $chunks)); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|