/
LaminasRouter.php
297 lines (253 loc) · 9.39 KB
/
LaminasRouter.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
<?php
declare(strict_types=1);
namespace Mezzio\Router;
use Laminas\Http\Exception\InvalidArgumentException;
use Laminas\Psr7Bridge\Psr7ServerRequest;
use Laminas\Router\Http\TreeRouteStack;
use Laminas\Router\RouteMatch;
use Laminas\Uri\Exception\InvalidUriPartException;
use Psr\Http\Message\ServerRequestInterface as PsrRequest;
use function array_key_exists;
use function array_merge;
use function array_reduce;
use function array_replace_recursive;
use function implode;
use function preg_match;
use function rtrim;
use function sprintf;
/**
* Router implementation that consumes laminas-mvc TreeRouteStack.
*
* This router implementation consumes the TreeRouteStack from laminas-mvc (the
* default router implementation in a Laminas application). The addRoute() method
* injects segment routes into the TreeRouteStack. To manage 405 (Method Not
* Allowed) errors, we inject a METHOD_NOT_ALLOWED_ROUTE route as a child
* route, at a priority lower than method-specific routes. If the request
* matches with this special route, we can send the HTTP allowed methods stored
* for that path.
*/
class LaminasRouter implements RouterInterface
{
public const METHOD_NOT_ALLOWED_ROUTE = 'method_not_allowed';
/**
* Store the HTTP methods allowed for each path.
*
* @var array<string, list<string>>
*/
private array $allowedMethodsByPath = [];
/**
* Map a named route to a Laminas route name to use for URI generation.
*
* @var array<string, string>
*/
private array $routeNameMap = [];
/** @var list<Route> */
private array $routes = [];
/**
* Routes aggregated to inject.
*
* @var list<Route>
*/
private array $routesToInject = [];
private TreeRouteStack $laminasRouter;
/**
* Lazy instantiates a TreeRouteStack if none is provided.
*/
public function __construct(?TreeRouteStack $router = null)
{
if (null === $router) {
$router = $this->createRouter();
}
$this->laminasRouter = $router;
}
public function addRoute(Route $route): void
{
$this->routesToInject[] = $route;
}
public function match(PsrRequest $request): RouteResult
{
// Must inject routes prior to matching.
$this->injectRoutes();
try {
$laminasRequest = Psr7ServerRequest::toLaminas($request, true);
} catch (InvalidArgumentException $e) {
$previous = $e->getPrevious();
if ($previous instanceof InvalidUriPartException) {
return RouteResult::fromRouteFailure(null);
}
throw $e;
}
$match = $this->laminasRouter->match($laminasRequest);
if (null === $match) {
// No route matched at all; to indicate that it's not due to the
// request method, we specify any request method was allowed.
return RouteResult::fromRouteFailure(Route::HTTP_METHOD_ANY);
}
return $this->marshalSuccessResultFromRouteMatch($match);
}
public function generateUri(string $name, array $substitutions = [], array $options = []): string
{
// Must inject routes prior to generating URIs.
$this->injectRoutes();
if (! $this->laminasRouter->hasRoute($name)) {
throw new Exception\RuntimeException(sprintf(
'Cannot generate URI based on route "%s"; route not found',
$name
));
}
$name = $this->routeNameMap[$name] ?? $name;
$options = array_merge($options, [
'name' => $name,
'only_return_path' => true,
]);
return $this->laminasRouter->assemble($substitutions, $options);
}
private function createRouter(): TreeRouteStack
{
return new TreeRouteStack();
}
/**
* Create a successful RouteResult from the given RouteMatch.
*/
private function marshalSuccessResultFromRouteMatch(RouteMatch $match): RouteResult
{
$params = $match->getParams();
if (array_key_exists(self::METHOD_NOT_ALLOWED_ROUTE, $params)) {
return RouteResult::fromRouteFailure(
$this->allowedMethodsByPath[$params[self::METHOD_NOT_ALLOWED_ROUTE]]
);
}
$routeName = $this->getMatchedRouteName($match->getMatchedRouteName());
$route = array_reduce($this->routes, static function (?Route $matched, Route $route) use ($routeName): ?Route {
if ($matched instanceof Route) {
return $matched;
}
// We store the route name already, so we can match on that
if ($routeName === $route->getName()) {
return $route;
}
return null;
}, null);
if (null === $route) {
// This should never happen, as Mezzio\Router\Route always
// ensures a non-empty route name. Marking as failed route to be
// consistent with other implementations.
return RouteResult::fromRouteFailure(Route::HTTP_METHOD_ANY);
}
return RouteResult::fromRoute($route, $params);
}
/**
* Create route configuration for matching one or more HTTP methods.
*/
private function createHttpMethodRoute(Route $route): array
{
return [
'type' => 'method',
'options' => [
'verb' => implode(',', $route->getAllowedMethods()),
'defaults' => [
'middleware' => $route->getMiddleware(),
],
],
];
}
/**
* Create the configuration for the "method not allowed" route.
*
* The specification is used for routes that have HTTP method negotiation;
* essentially, this is a route that will always match, but *after* the
* HTTP method route has already failed. By checking for this route later,
* we can return a 405 response with the allowed methods.
*/
private function createMethodNotAllowedRoute(string $path): array
{
return [
'type' => 'regex',
'priority' => -1,
'options' => [
'regex' => '',
'defaults' => [
self::METHOD_NOT_ALLOWED_ROUTE => $path,
],
'spec' => '',
],
];
}
/**
* Calculate the route name.
*
* Routes will generally match the child HTTP method routes, which will not
* match the names they were registered with; this method strips the method
* route name if present.
*/
private function getMatchedRouteName(string $name): string
{
// Check for <name>/GET:POST style route names; if so, strip off the
// child route matching the method.
if (preg_match('/(?P<name>.+)\/([!#$%&\'*+.^_`\|~0-9a-z-]+:?)+$/i', $name, $matches)) {
return $matches['name'];
}
// Otherwise, just use the name.
return rtrim($name, '/');
}
/**
* Inject any unprocessed routes into the underlying router implementation.
*/
private function injectRoutes(): void
{
foreach ($this->routesToInject as $index => $route) {
$this->injectRoute($route);
$this->routes[] = $route;
unset($this->routesToInject[$index]);
}
}
/**
* Inject route into the underlying router implemetation.
*/
private function injectRoute(Route $route): void
{
$name = $route->getName();
$path = $route->getPath();
$options = $route->getOptions();
$options = array_replace_recursive($options, [
'route' => $path,
'defaults' => [
'middleware' => $route->getMiddleware(),
],
]);
$allowedMethods = $route->getAllowedMethods();
if (Route::HTTP_METHOD_ANY === $allowedMethods) {
$this->laminasRouter->addRoute($name, [
'type' => 'segment',
'options' => $options,
]);
$this->routeNameMap[$name] = $name;
return;
}
// Remove the middleware from the segment route in favor of method route
unset($options['defaults']['middleware']);
if (empty($options['defaults'])) {
unset($options['defaults']);
}
$httpMethodRouteName = implode(':', $allowedMethods);
$httpMethodRoute = $this->createHttpMethodRoute($route);
$methodNotAllowedRoute = $this->createMethodNotAllowedRoute($path);
$spec = [
'type' => 'segment',
'options' => $options,
'may_terminate' => false,
'child_routes' => [
$httpMethodRouteName => $httpMethodRoute,
self::METHOD_NOT_ALLOWED_ROUTE => $methodNotAllowedRoute,
],
];
if (array_key_exists($path, $this->allowedMethodsByPath)) {
$allowedMethods = array_merge($this->allowedMethodsByPath[$path], $allowedMethods);
// Remove the method not allowed route as it is already present for the path
unset($spec['child_routes'][self::METHOD_NOT_ALLOWED_ROUTE]);
}
$this->laminasRouter->addRoute($name, $spec);
$this->allowedMethodsByPath[$path] = $allowedMethods;
$this->routeNameMap[$name] = sprintf('%s/%s', $name, $httpMethodRouteName);
}
}