Completed
Pull Request — master (#16)
by Arnaud
48:07 queued 29:02
created

SymfonyUrlProvider::getCollection()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 38
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

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