Test Failed
Push — feature/html-code-handler ( 69c349...0406d3 )
by Arnaud
02:18
created

UrlProviderRegistry   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 79
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 79
rs 10
c 0
b 0
f 0
wmc 9

5 Methods

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