forked from symfony-cmf/Routing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChainRouter.php
356 lines (313 loc) · 10.8 KB
/
ChainRouter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
<?php
/*
* This file is part of the Symfony CMF package.
*
* (c) 2011-2015 Symfony CMF
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Cmf\Component\Routing;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RequestContextAwareInterface;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface;
use Psr\Log\LoggerInterface;
/**
* The ChainRouter allows to combine several routers to try in a defined order.
*
* @author Henrik Bjornskov <henrik@bjrnskov.dk>
* @author Magnus Nordlander <magnus@e-butik.se>
*/
class ChainRouter implements ChainRouterInterface, WarmableInterface
{
/**
* @var RequestContext
*/
private $context;
/**
* Array of arrays of routers grouped by priority.
*
* @var array
*/
private $routers = array();
/**
* @var RouterInterface[] Array of routers, sorted by priority
*/
private $sortedRouters;
/**
* @var RouteCollection
*/
private $routeCollection;
/**
* @var null|LoggerInterface
*/
protected $logger;
/**
* @param LoggerInterface $logger
*/
public function __construct(LoggerInterface $logger = null)
{
$this->logger = $logger;
}
/**
* @return RequestContext
*/
public function getContext()
{
return $this->context;
}
/**
* {@inheritdoc}
*/
public function add($router, $priority = 0)
{
if (!$router instanceof RouterInterface
&& !($router instanceof RequestMatcherInterface && $router instanceof UrlGeneratorInterface)
) {
throw new \InvalidArgumentException(sprintf('%s is not a valid router.', get_class($router)));
}
if (empty($this->routers[$priority])) {
$this->routers[$priority] = array();
}
$this->routers[$priority][] = $router;
$this->sortedRouters = array();
}
/**
* {@inheritdoc}
*/
public function all()
{
if (empty($this->sortedRouters)) {
$this->sortedRouters = $this->sortRouters();
// setContext() is done here instead of in add() to avoid fatal errors when clearing and warming up caches
// See https://github.com/symfony-cmf/Routing/pull/18
$context = $this->getContext();
if (null !== $context) {
foreach ($this->sortedRouters as $router) {
if ($router instanceof RequestContextAwareInterface) {
$router->setContext($context);
}
}
}
}
return $this->sortedRouters;
}
/**
* Sort routers by priority.
* The highest priority number is the highest priority (reverse sorting).
*
* @return RouterInterface[]
*/
protected function sortRouters()
{
$sortedRouters = array();
krsort($this->routers);
foreach ($this->routers as $routers) {
$sortedRouters = array_merge($sortedRouters, $routers);
}
return $sortedRouters;
}
/**
* {@inheritdoc}
*
* Loops through all routes and tries to match the passed url.
*
* Note: You should use matchRequest if you can.
*/
public function match($pathinfo)
{
return $this->doMatch($pathinfo);
}
/**
* {@inheritdoc}
*
* Loops through all routes and tries to match the passed request.
*/
public function matchRequest(Request $request)
{
return $this->doMatch($request->getPathInfo(), $request);
}
/**
* Loops through all routers and tries to match the passed request or url.
*
* At least the url must be provided, if a request is additionally provided
* the request takes precedence.
*
* @param string $pathinfo
* @param Request $request
*
* @return array An array of parameters
*
* @throws ResourceNotFoundException If no router matched.
*/
private function doMatch($pathinfo, Request $request = null)
{
$methodNotAllowed = null;
$requestForMatching = $request;
foreach ($this->all() as $router) {
try {
// the request/url match logic is the same as in Symfony/Component/HttpKernel/EventListener/RouterListener.php
// matching requests is more powerful than matching URLs only, so try that first
if ($router instanceof RequestMatcherInterface) {
if (empty($requestForMatching)) {
$requestForMatching = $this->rebuildRequest($pathinfo);
}
return $router->matchRequest($requestForMatching);
}
// every router implements the match method
return $router->match($pathinfo);
} catch (ResourceNotFoundException $e) {
if ($this->logger) {
$this->logger->debug('Router '.get_class($router).' was not able to match, message "'.$e->getMessage().'"');
}
// Needs special care
} catch (MethodNotAllowedException $e) {
if ($this->logger) {
$this->logger->debug('Router '.get_class($router).' throws MethodNotAllowedException with message "'.$e->getMessage().'"');
}
$methodNotAllowed = $e;
}
}
$info = $request
? "this request\n$request"
: "url '$pathinfo'";
throw $methodNotAllowed ?: new ResourceNotFoundException("None of the routers in the chain matched $info");
}
/**
* {@inheritdoc}
*
* Loops through all registered routers and returns a router if one is found.
* It will always return the first route generated.
*/
public function generate($name, $parameters = array(), $absolute = UrlGeneratorInterface::ABSOLUTE_PATH)
{
$debug = array();
foreach ($this->all() as $router) {
// if $router does not announce it is capable of handling
// non-string routes and $name is not a string, continue
if ($name && !is_string($name) && !$router instanceof VersatileGeneratorInterface) {
continue;
}
// If $router is versatile and doesn't support this route name, continue
if ($router instanceof VersatileGeneratorInterface && !$router->supports($name)) {
continue;
}
try {
return $router->generate($name, $parameters, $absolute);
} catch (RouteNotFoundException $e) {
$hint = $this->getErrorMessage($name, $router, $parameters);
$debug[] = $hint;
if ($this->logger) {
$this->logger->debug('Router '.get_class($router)." was unable to generate route. Reason: '$hint': ".$e->getMessage());
}
}
}
if ($debug) {
$debug = array_unique($debug);
$info = implode(', ', $debug);
} else {
$info = $this->getErrorMessage($name);
}
throw new RouteNotFoundException(sprintf('None of the chained routers were able to generate route: %s', $info));
}
/**
* Rebuild the request object from a URL with the help of the RequestContext.
*
* If the request context is not set, this simply returns the request object built from $uri.
*
* @param string $pathinfo
*
* @return Request
*/
private function rebuildRequest($pathinfo)
{
if (!$this->context) {
return Request::create('http://localhost'.$pathinfo);
}
$uri = $pathinfo;
$server = array();
if ($this->context->getBaseUrl()) {
$uri = $this->context->getBaseUrl().$pathinfo;
$server['SCRIPT_FILENAME'] = $this->context->getBaseUrl();
$server['PHP_SELF'] = $this->context->getBaseUrl();
}
$host = $this->context->getHost() ?: 'localhost';
if ('https' === $this->context->getScheme() && 443 !== $this->context->getHttpsPort()) {
$host .= ':'.$this->context->getHttpsPort();
}
if ('http' === $this->context->getScheme() && 80 !== $this->context->getHttpPort()) {
$host .= ':'.$this->context->getHttpPort();
}
$uri = $this->context->getScheme().'://'.$host.$uri.'?'.$this->context->getQueryString();
return Request::create($uri, $this->context->getMethod(), $this->context->getParameters(), array(), array(), $server);
}
private function getErrorMessage($name, $router = null, $parameters = null)
{
if ($router instanceof VersatileGeneratorInterface) {
$displayName = $router->getRouteDebugMessage($name, $parameters);
} elseif (is_object($name)) {
$displayName = method_exists($name, '__toString')
? (string) $name
: get_class($name)
;
} else {
$displayName = (string) $name;
}
return "Route '$displayName' not found";
}
/**
* {@inheritdoc}
*/
public function setContext(RequestContext $context)
{
foreach ($this->all() as $router) {
if ($router instanceof RequestContextAwareInterface) {
$router->setContext($context);
}
}
$this->context = $context;
}
/**
* {@inheritdoc}
*
* check for each contained router if it can warmup
*/
public function warmUp($cacheDir)
{
foreach ($this->all() as $router) {
if ($router instanceof WarmableInterface) {
$router->warmUp($cacheDir);
}
}
}
/**
* {@inheritdoc}
*/
public function getRouteCollection()
{
if (!$this->routeCollection instanceof RouteCollection) {
$this->routeCollection = new ChainRouteCollection();
foreach ($this->all() as $router) {
$this->routeCollection->addCollection($router->getRouteCollection());
}
}
return $this->routeCollection;
}
/**
* Identify if any routers have been added into the chain yet.
*
* @return bool
*/
public function hasRouters()
{
return !empty($this->routers);
}
}