1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of Flight Routing. |
7
|
|
|
* |
8
|
|
|
* PHP version 7.1 and above required |
9
|
|
|
* |
10
|
|
|
* @author Divine Niiquaye Ibok <[email protected]> |
11
|
|
|
* @copyright 2019 Biurad Group (https://biurad.com/) |
12
|
|
|
* @license https://opensource.org/licenses/BSD-3-Clause License |
13
|
|
|
* |
14
|
|
|
* For the full copyright and license information, please view the LICENSE |
15
|
|
|
* file that was distributed with this source code. |
16
|
|
|
*/ |
17
|
|
|
|
18
|
|
|
namespace Flight\Routing; |
19
|
|
|
|
20
|
|
|
use DivineNii\Invoker\Interfaces\InvokerInterface; |
21
|
|
|
use DivineNii\Invoker\Invoker; |
22
|
|
|
use Flight\Routing\Exceptions\DuplicateRouteException; |
23
|
|
|
use Flight\Routing\Exceptions\MethodNotAllowedException; |
24
|
|
|
use Flight\Routing\Exceptions\RouteNotFoundException; |
25
|
|
|
use Flight\Routing\Exceptions\UriHandlerException; |
26
|
|
|
use Flight\Routing\Handlers\RouteHandler; |
27
|
|
|
use Flight\Routing\Interfaces\MatcherDumperInterface; |
28
|
|
|
use Flight\Routing\Interfaces\RouteMatcherInterface; |
29
|
|
|
use Flight\Routing\Interfaces\RouterInterface; |
30
|
|
|
use Laminas\Stratigility\MiddlewarePipe; |
31
|
|
|
use Laminas\Stratigility\MiddlewarePipeInterface; |
32
|
|
|
use Psr\Http\Message\ResponseFactoryInterface; |
33
|
|
|
use Psr\Http\Message\ResponseInterface; |
34
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
35
|
|
|
use Psr\Http\Message\UriFactoryInterface; |
36
|
|
|
use Psr\Http\Message\UriInterface; |
37
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
38
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Aggregate routes for matching and Dispatching. |
42
|
|
|
* |
43
|
|
|
* Internally, the class performs some checks for duplicate routes when |
44
|
|
|
* attaching via one of the exposed methods, and will raise an exception when a |
45
|
|
|
* collision occurs. |
46
|
|
|
* |
47
|
|
|
* @author Divine Niiquaye Ibok <[email protected]> |
48
|
|
|
*/ |
49
|
|
|
class Router implements RouterInterface, RequestHandlerInterface |
50
|
77 |
|
{ |
51
|
|
|
use Traits\RouterTrait; |
52
|
|
|
|
53
|
|
|
/** @var MiddlewarePipeInterface */ |
54
|
|
|
private $pipeline; |
55
|
|
|
|
56
|
77 |
|
/** |
57
|
77 |
|
* @param array<string,mixed> $options |
58
|
77 |
|
*/ |
59
|
77 |
|
public function __construct( |
60
|
77 |
|
ResponseFactoryInterface $responseFactory, |
61
|
|
|
UriFactoryInterface $uriFactory, |
62
|
|
|
?InvokerInterface $resolver = null, |
63
|
|
|
array $options = [] |
64
|
|
|
) { |
65
|
|
|
$this->uriFactory = $uriFactory; |
66
|
|
|
$this->responseFactory = $responseFactory; |
67
|
|
|
$this->resolver = new RouteResolver($resolver ?? new Invoker()); |
68
|
|
|
|
69
|
62 |
|
$this->setOptions($options); |
70
|
|
|
$this->routes = new RouteCollection(false); |
71
|
62 |
|
$this->pipeline = new MiddlewarePipe(); |
72
|
62 |
|
} |
73
|
|
|
|
74
|
62 |
|
/** |
75
|
1 |
|
* Sets options. |
76
|
1 |
|
* |
77
|
|
|
* Available options: |
78
|
|
|
* |
79
|
|
|
* * cache_dir: The cache directory (or null to disable caching) |
80
|
62 |
|
* * debug: Whether to enable debugging or not (false by default) |
81
|
|
|
* * namespace: Set Namespace for route handlers/controllers |
82
|
62 |
|
* * matcher_class: The name of a RouteMatcherInterface implementation |
83
|
1 |
|
* * matcher_dumper_class: The name of a MatcherDumperInterface implementation |
84
|
|
|
* * options_skip: Whether to serve a response on HTTP request OPTIONS method (false by default) |
85
|
|
|
* |
86
|
62 |
|
* @throws \InvalidArgumentException When unsupported option is provided |
87
|
|
|
*/ |
88
|
|
|
public function setOptions(array $options): void |
89
|
|
|
{ |
90
|
|
|
$this->options = [ |
91
|
|
|
'cache_dir' => null, |
92
|
|
|
'debug' => false, |
93
|
57 |
|
'options_skip' => false, |
94
|
|
|
'namespace' => null, |
95
|
57 |
|
'matcher_class' => Matchers\SimpleRouteMatcher::class, |
96
|
57 |
|
'matcher_dumper_class' => Matchers\SimpleRouteDumper::class, |
97
|
|
|
]; |
98
|
57 |
|
|
99
|
|
|
// check option names and live merge, if errors are encountered Exception will be thrown |
100
|
|
|
$invalid = []; |
101
|
|
|
|
102
|
|
|
foreach ($options as $key => $value) { |
103
|
|
|
if (\array_key_exists($key, $this->options)) { |
104
|
|
|
$this->options[$key] = $value; |
105
|
|
|
} else { |
106
|
|
|
$invalid[] = $key; |
107
|
|
|
} |
108
|
|
|
} |
109
|
|
|
|
110
|
|
|
if (!empty($invalid)) { |
111
|
|
|
throw new \InvalidArgumentException( |
112
|
|
|
\sprintf('The Router does not support the following options: "%s".', \implode('", "', $invalid)) |
113
|
|
|
); |
114
|
|
|
} |
115
|
|
|
|
116
|
|
|
if ($this->options['debug']) { |
117
|
|
|
$this->debug = new DebugRoute(); |
118
|
|
|
} |
119
|
|
|
|
120
|
|
|
// Set the cache_file for caching compiled routes. |
121
|
|
|
if (isset($this->options['cache_dir'])) { |
122
|
4 |
|
$this->options['cache_file'] = $this->options['cache_dir'] . '/compiled_routes.php'; |
123
|
|
|
} |
124
|
|
|
} |
125
|
4 |
|
|
126
|
1 |
|
/** |
127
|
1 |
|
* This is true if debug mode is false and cached routes exists. |
128
|
1 |
|
*/ |
129
|
1 |
|
public function isFrozen(): bool |
130
|
1 |
|
{ |
131
|
|
|
if ($this->options['debug']) { |
132
|
1 |
|
return false; |
133
|
|
|
} |
134
|
|
|
|
135
|
|
|
return \file_exists($this->options['cache_file'] ?? ''); |
136
|
3 |
|
} |
137
|
|
|
|
138
|
|
|
/** |
139
|
|
|
* Adds the given route(s) to the router |
140
|
|
|
* |
141
|
|
|
* @param Route ...$routes |
142
|
|
|
* |
143
|
|
|
* @throws DuplicateRouteException |
144
|
|
|
*/ |
145
|
|
|
public function addRoute(Route ...$routes): void |
146
|
|
|
{ |
147
|
|
|
foreach ($routes as $route) { |
148
|
|
|
if (null === $name = $route->get('name')) { |
149
|
|
|
$route->bind($name = $route->generateRouteName('')); |
150
|
51 |
|
} |
151
|
|
|
|
152
|
|
|
if (null !== $this->routes->find($name)) { |
153
|
51 |
|
throw new DuplicateRouteException( |
154
|
|
|
\sprintf('A route with the name "%s" already exists.', $name) |
155
|
47 |
|
); |
156
|
4 |
|
} |
157
|
4 |
|
|
158
|
4 |
|
$this->routes->add($route); |
159
|
4 |
|
} |
160
|
|
|
} |
161
|
|
|
|
162
|
|
|
/** |
163
|
|
|
* Attach middleware to the pipeline. |
164
|
43 |
|
* |
165
|
|
|
* @param array<string,mixed>|callable|MiddlewareInterface|RequestHandlerInterface|string $middleware |
166
|
43 |
|
*/ |
167
|
1 |
|
public function pipe($middleware): void |
168
|
|
|
{ |
169
|
|
|
if (!$middleware instanceof MiddlewareInterface) { |
170
|
43 |
|
$middleware = $this->resolveMiddleware($middleware); |
171
|
|
|
} |
172
|
|
|
|
173
|
|
|
$this->pipeline->pipe($middleware); |
174
|
|
|
} |
175
|
|
|
|
176
|
44 |
|
/** |
177
|
|
|
* {@inheritdoc} |
178
|
|
|
*/ |
179
|
44 |
|
public function getCollection(): RouteCollection |
180
|
43 |
|
{ |
181
|
|
|
return $this->routes; |
182
|
|
|
} |
183
|
38 |
|
|
184
|
|
|
/** |
185
|
38 |
|
* {@inheritdoc} |
186
|
38 |
|
* |
187
|
38 |
|
* @return UriInterface of fully qualified URL for named route |
188
|
38 |
|
*/ |
189
|
|
|
public function generateUri(string $routeName, array $parameters = [], array $queryParams = []): UriInterface |
190
|
38 |
|
{ |
191
|
38 |
|
$createUri = (string) $this->getMatcher()->generateUri($routeName, $parameters, $queryParams); |
192
|
38 |
|
|
193
|
|
|
return $this->uriFactory->createUri($createUri); |
194
|
38 |
|
} |
195
|
|
|
|
196
|
38 |
|
/** |
197
|
38 |
|
* Looks for a route that matches the given request |
198
|
1 |
|
* |
199
|
|
|
* @throws MethodNotAllowedException |
200
|
|
|
* @throws UriHandlerException |
201
|
|
|
* @throws RouteNotFoundException |
202
|
38 |
|
*/ |
203
|
|
|
public function match(ServerRequestInterface $request): Route |
204
|
38 |
|
{ |
205
|
|
|
// Get the request matching format. |
206
|
|
|
$route = $this->getMatcher()->match($request); |
207
|
|
|
|
208
|
|
|
if (!$route instanceof Route) { |
209
|
|
|
throw new RouteNotFoundException( |
210
|
|
|
\sprintf( |
211
|
|
|
'Unable to find the controller for path "%s". The route is wrongly configured.', |
212
|
|
|
$request->getUri()->getPath() |
213
|
54 |
|
) |
214
|
|
|
); |
215
|
54 |
|
} |
216
|
|
|
|
217
|
54 |
|
$this->mergeDefaults($route); |
218
|
1 |
|
|
219
|
|
|
if ($this->options['debug']) { |
220
|
|
|
$this->debug->setMatched(new DebugRoute($route->get('name'), $route)); |
|
|
|
|
221
|
54 |
|
} |
222
|
2 |
|
|
223
|
|
|
return $this->route = clone $route; |
224
|
|
|
} |
225
|
54 |
|
|
226
|
|
|
/** |
227
|
|
|
* {@inheritDoc} |
228
|
|
|
*/ |
229
|
|
|
public function handle(ServerRequestInterface $request): ResponseInterface |
230
|
|
|
{ |
231
|
|
|
// This is to aid request made from javascript using cors, eg: using axios. |
232
|
|
|
// Midddlware support is added, so it make it easier to add "cors" settings to the response and request |
233
|
|
|
if ($this->options['options_skip'] && \strtolower($request->getMethod()) === 'options') { |
234
|
|
|
return $this->handleOptionsResponse($request); |
235
|
|
|
} |
236
|
|
|
|
237
|
|
|
$route = $this->match($request); |
238
|
|
|
$handler = $this->route->getController(); |
|
|
|
|
239
|
|
|
|
240
|
|
|
if (!$handler instanceof RequestHandlerInterface) { |
241
|
|
|
$handler = new RouteHandler( |
242
|
|
|
function (ServerRequestInterface $request, ResponseInterface $response) use ($route) { |
243
|
|
|
if (isset($this->options['namespace'])) { |
244
|
|
|
$this->resolver->setNamespace($this->options['namespace']); |
245
|
|
|
} |
246
|
|
|
|
247
|
|
|
return ($this->resolver)($request, $response, $route); |
248
|
|
|
}, |
249
|
|
|
$this->responseFactory |
250
|
|
|
); |
251
|
|
|
} |
252
|
|
|
|
253
|
|
|
try { |
254
|
|
|
$this->addMiddleware(...$this->resolveMiddlewares($route)); |
255
|
|
|
|
256
|
|
|
return $this->pipeline->process($request->withAttribute(Route::class, $route), $handler); |
257
|
|
|
} finally { |
258
|
|
|
if ($this->options['debug']) { |
259
|
|
|
foreach ($this->debug->getProfiles() as $profiler) { |
260
|
|
|
$profiler->leave(); |
261
|
|
|
} |
262
|
|
|
} |
263
|
|
|
} |
264
|
|
|
} |
265
|
|
|
|
266
|
|
|
/** |
267
|
|
|
* Gets the RouteMatcherInterface instance associated with this Router. |
268
|
|
|
*/ |
269
|
|
|
public function getMatcher(): RouteMatcherInterface |
270
|
|
|
{ |
271
|
|
|
if (null !== $this->matcher) { |
272
|
|
|
return $this->matcher; |
273
|
|
|
} elseif ($this->isFrozen()) { |
274
|
|
|
return $this->matcher = $this->getDumper($this->options['cache_file']); |
275
|
|
|
} |
276
|
|
|
|
277
|
|
|
if (!$this->options['debug'] && isset($this->options['cache_file'])) { |
278
|
|
|
$dumper = $this->getDumper($this->routes); |
279
|
|
|
|
280
|
|
|
if ($dumper instanceof MatcherDumperInterface) { |
281
|
|
|
$cacheDir = $this->options['cache_dir']; |
282
|
|
|
$cacheFile = $this->options['cache_file']; |
283
|
|
|
|
284
|
|
|
if (!\file_exists($cacheDir)) { |
285
|
|
|
@\mkdir($cacheDir, 0777, true); |
|
|
|
|
286
|
|
|
} |
287
|
|
|
|
288
|
|
|
\file_put_contents($cacheFile, $dumper->dump()); |
289
|
|
|
|
290
|
|
|
if ( |
291
|
|
|
\function_exists('opcache_invalidate') && |
292
|
|
|
\filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN) |
293
|
|
|
) { |
294
|
|
|
@opcache_invalidate($cacheFile, true); |
|
|
|
|
295
|
|
|
} |
296
|
|
|
} |
297
|
|
|
|
298
|
|
|
return $this->matcher = $dumper; |
299
|
|
|
} |
300
|
|
|
|
301
|
|
|
/** @var RouteMatcherInterface $matcher */ |
302
|
|
|
$matcher = new $this->options['matcher_class']($this->routes); |
303
|
|
|
|
304
|
|
|
return $this->matcher = $matcher; |
305
|
|
|
} |
306
|
|
|
|
307
|
|
|
/** |
308
|
|
|
* @param RouteCollection|string $routes |
309
|
|
|
*/ |
310
|
|
|
private function getDumper($routes): RouteMatcherInterface |
311
|
|
|
{ |
312
|
|
|
return new $this->options['matcher_dumper_class']($routes); |
313
|
|
|
} |
314
|
|
|
|
315
|
|
|
/** |
316
|
|
|
* We have allowed middleware from router to run on response due to |
317
|
|
|
* |
318
|
|
|
* @return \Psr\Http\Message\ResponseInterface |
319
|
|
|
*/ |
320
|
|
|
private function handleOptionsResponse(ServerRequestInterface $request): ResponseInterface |
321
|
|
|
{ |
322
|
|
|
return $this->pipeline->process( |
323
|
|
|
$request, |
324
|
|
|
new Handlers\CallbackHandler( |
325
|
|
|
function (ServerRequestInterface $request): ResponseInterface { |
|
|
|
|
326
|
|
|
return $this->responseFactory->createResponse(); |
327
|
|
|
} |
328
|
|
|
) |
329
|
|
|
); |
330
|
|
|
} |
331
|
|
|
} |
332
|
|
|
|