Test Failed
Push — feature/html-code-handler ( 5d4979...10827c )
by Arnaud
02:41
created

SymfonyUrlProvider::hasRouteRequirements()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace LAG\SmokerBundle\Url\Provider;
4
5
use Generator;
6
use LAG\SmokerBundle\Exception\Exception;
7
use LAG\SmokerBundle\Url\Collection\UrlCollection;
8
use LAG\SmokerBundle\Url\Requirements\Registry\RequirementsProviderRegistry;
9
use LAG\SmokerBundle\Url\Url;
10
use Symfony\Component\OptionsResolver\OptionsResolver;
11
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
12
use Symfony\Component\Routing\Exception\NoConfigurationException;
13
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
14
use Symfony\Component\Routing\Route;
15
use Symfony\Component\Routing\Router;
16
use Symfony\Component\Routing\RouterInterface;
17
18
class SymfonyUrlProvider implements UrlProviderInterface
19
{
20
    /**
21
     * @var RouterInterface
22
     */
23
    protected $router;
24
25
    /**
26
     * @var RequirementsProviderRegistry
27
     */
28
    protected $requirementsProviderRegistry;
29
30
    /**
31
     * @var array
32
     */
33
    protected $routes;
34
35
    /**
36
     * @var array
37
     */
38
    protected $mapping;
39
40
    /**
41
     * @var array
42
     */
43
    protected $routingConfiguration;
44
45
    /**
46
     * SymfonyRoutingProvider constructor.
47
     *
48
     * @param array                        $routingConfiguration
49
     * @param array                        $routes
50
     * @param array                        $mapping
51
     * @param RouterInterface              $router
52
     * @param RequirementsProviderRegistry $requirementsProviderRegistry
53
     */
54
    public function __construct(
55
        array $routingConfiguration,
56
        array $routes,
57
        array $mapping,
58
        RouterInterface $router,
59
        RequirementsProviderRegistry $requirementsProviderRegistry
60
    ) {
61
        $this->router = $router;
62
        $this->requirementsProviderRegistry = $requirementsProviderRegistry;
63
        $this->routes = $routes;
64
        $this->mapping = $mapping;
65
        $this->routingConfiguration = $routingConfiguration;
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function getName(): string
72
    {
73
        return 'symfony';
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79
    public function supports(string $url): bool
80
    {
81
        $urlParts = parse_url($url);
82
83
        if (!is_array($urlParts) || !key_exists('path', $urlParts)) {
0 ignored issues
show
introduced by
The condition is_array($urlParts) is always true.
Loading history...
84
            return false;
85
        }
86
        $path = $urlParts['path'];
87
88
        try {
89
            $this->router->match($path);
90
        } catch (NoConfigurationException $exception) {
91
            return false;
92
        } catch (ResourceNotFoundException $exception) {
93
            return false;
94
        } catch (MethodNotAllowedException $exception) {
95
            return false;
96
        }
97
98
        return true;
99
    }
100
101
    /**
102
     * {@inheritdoc}
103
     */
104
    public function match(string $url): array
105
    {
106
        $urlParts = parse_url($url);
107
108
        if (!is_array($urlParts) || !key_exists('path', $urlParts)) {
0 ignored issues
show
introduced by
The condition is_array($urlParts) is always true.
Loading history...
109
            throw new Exception('Can not extract the path from the url "'.$url.'"');
110
        }
111
        $path = $urlParts['path'];
112
        $pathInfo = $this->router->match($path);
113
114
        if (!key_exists('path', $pathInfo)) {
115
            $pathInfo['path'] = $path;
116
        }
117
118
        return $pathInfo;
119
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124
    public function configure(OptionsResolver $resolver): void
125
    {
126
    }
127
128
    /**
129
     * {@inheritdoc}
130
     */
131
    public function getCollection(array $options = []): UrlCollection
132
    {
133
        $collection = new UrlCollection();
134
        $routes = $this->router->getRouteCollection()->all();
135
        $this->defineContext();
136
137
        foreach ($this->routes as $routeName => $routeOptions) {
138
            // The provided routes should be present in the Symfony routing
139
            if (!key_exists($routeName, $routes)) {
140
                continue;
141
            }
142
            $route = $routes[$routeName];
143
144
            // Two cases: if the route is dynamic, we should generate an url for each requirements provided by
145
            // requirements providers. If the route is static, one url is generated
146
            if ($this->hasRouteRequirements($route)) {
147
                $routeParametersCollection = $this->getRouteRequirements($routeName);
148
149
                foreach ($routeParametersCollection as $routeParameters) {
150
                    // Use the absolute url parameters to preserve the route configuration, especially if an host is
151
                    // configured in the Symfony routing
152
                    $url = $this->router->generate($routeName, $routeParameters, Router::ABSOLUTE_URL);
153
154
                    $collection->add(new Url($url, $this->getName()));
155
                }
156
            } else {
157
                $url = $this->router->generate($routeName, [], Router::ABSOLUTE_URL);
158
                $collection->add(new Url($url, $this->getName()));
159
            }
160
        }
161
162
        return $collection;
163
    }
164
165
    /**
166
     * Return a generator containing each set of parameters according to the providers.
167
     *
168
     * @param string $routeName
169
     *
170
     * @return Generator
171
     */
172
    protected function getRouteRequirements(string $routeName): Generator
173
    {
174
        foreach ($this->requirementsProviderRegistry->all() as $requirementsProvider) {
175
            if (!$requirementsProvider->supports($routeName)) {
176
                continue;
177
            }
178
            $requirements = $requirementsProvider->getRequirements($routeName);
179
180
            foreach ($requirements as $values) {
181
                $routeParameters = [];
182
183
                foreach ($values as $name => $value) {
184
                    $routeParameters[$name] = $value;
185
                }
186
                yield $routeParameters;
187
            }
188
        }
189
    }
190
191
    /**
192
     * Return true if the given route requires parameters to be generated.
193
     *
194
     * @param Route $route
195
     *
196
     * @return bool
197
     */
198
    protected function hasRouteRequirements(Route $route): bool
199
    {
200
        if (0 < count($route->getRequirements())) {
201
            return true;
202
        }
203
204
        if (preg_match('/\{(.*?)\}/', $route->getPath())) {
205
            return true;
206
        }
207
208
        return false;
209
    }
210
211
    protected function defineContext(): void
212
    {
213
        $context = $this->router->getContext();
214
        $context->setScheme($this->routingConfiguration['scheme']);
215
        $context->setHost($this->routingConfiguration['host']);
216
        $context->setBaseUrl($this->routingConfiguration['base_url']);
217
218
        if ('https' === $context->getScheme()) {
219
            $context->setHttpsPort($this->routingConfiguration['port']);
220
        } else {
221
            $context->setHttpPort($this->routingConfiguration['port']);
222
        }
223
    }
224
}
225