1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace LAG\SmokerBundle\Url\Registry; |
4
|
|
|
|
5
|
|
|
use LAG\SmokerBundle\Contracts\Url\Provider\UrlProviderInterface; |
6
|
|
|
use LAG\SmokerBundle\Exception\Exception; |
7
|
|
|
use LAG\SmokerBundle\Url\UrlInfo; |
8
|
|
|
|
9
|
|
|
class UrlProviderRegistry |
10
|
|
|
{ |
11
|
|
|
protected $registry = []; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Add a new url provider to the registry. If a provider with the same name is already registered, an exception will |
15
|
|
|
* be thrown. |
16
|
|
|
* |
17
|
|
|
* @throws Exception |
18
|
|
|
*/ |
19
|
5 |
|
public function add(UrlProviderInterface $provider): void |
20
|
|
|
{ |
21
|
5 |
|
if ($this->has($provider->getName())) { |
22
|
1 |
|
throw new Exception('The provider "'.$provider->getName().'" is already registered'); |
23
|
|
|
} |
24
|
5 |
|
$this->registry[$provider->getName()] = $provider; |
25
|
5 |
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Return an url provider matching the given name. If none exists, an exception will be thrown? |
29
|
|
|
* |
30
|
|
|
* @throws Exception |
31
|
|
|
*/ |
32
|
3 |
|
public function get(string $name): UrlProviderInterface |
33
|
|
|
{ |
34
|
3 |
|
if (!$this->has($name)) { |
35
|
1 |
|
throw new Exception('The provider "'.$name.'" is not registered'); |
36
|
|
|
} |
37
|
|
|
|
38
|
2 |
|
return $this->registry[$name]; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Return true if a provider with the given name is registered in the registry. |
43
|
|
|
*/ |
44
|
6 |
|
public function has(string $name): bool |
45
|
|
|
{ |
46
|
6 |
|
return array_key_exists($name, $this->registry); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @return UrlProviderInterface[] |
51
|
|
|
*/ |
52
|
3 |
|
public function all(): array |
53
|
|
|
{ |
54
|
3 |
|
return $this->registry; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Return information about the given url like the http parts of the url (host, scheme...), the route name and some |
59
|
|
|
* extra data according to the provider. |
60
|
|
|
* |
61
|
|
|
* @throws Exception |
62
|
|
|
*/ |
63
|
2 |
|
public function match(string $url): UrlInfo |
64
|
|
|
{ |
65
|
2 |
|
foreach ($this->all() as $provider) { |
66
|
1 |
|
if (!$provider->supports($url)) { |
67
|
1 |
|
continue; |
68
|
|
|
} |
69
|
|
|
// Return only the first matching result |
70
|
1 |
|
return $provider->match($url); |
71
|
|
|
} |
72
|
|
|
|
73
|
1 |
|
throw new Exception('The path "'.$url.'" is not supported by an url provider'); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|