1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Air\Routing\FastRoute; |
4
|
|
|
|
5
|
|
|
use Air\Routing\Router\Router; |
6
|
|
|
use Air\HTTP\Request\RequestInterface; |
7
|
|
|
use FastRoute\RouteCollector; |
8
|
|
|
use FastRoute\Dispatcher; |
9
|
|
|
use Air\Routing\ResolvedRequest\ResolvedRequest; |
10
|
|
|
use Air\Routing\ResolvedRequest\ResolvedRequestInterface; |
11
|
|
|
use Exception; |
12
|
|
|
use OutOfRangeException; |
13
|
|
|
|
14
|
|
|
class FastRoute extends Router |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @param RequestInterface $request A request. |
18
|
|
|
* @return ResolvedRequestInterface |
19
|
|
|
* @throws OutOfRangeException |
20
|
|
|
* @throws Exception |
21
|
|
|
*/ |
22
|
|
|
public function route(RequestInterface $request) |
23
|
|
|
{ |
24
|
|
|
if (!is_null($this->cachePath)) { |
25
|
|
|
$dispatcher = \FastRoute\cachedDispatcher( |
26
|
|
|
function(RouteCollector $collector) { |
27
|
|
|
foreach ($this->routes as $route) { |
28
|
|
|
$collector->addRoute( |
29
|
|
|
$route->getRequestType(), |
30
|
|
|
$route->getUri(), |
31
|
|
|
serialize($route) |
32
|
|
|
); |
33
|
|
|
} |
34
|
|
|
}, [ |
35
|
|
|
'cacheFile' => $this->cachePath |
36
|
|
|
] |
37
|
|
|
); |
38
|
|
|
} else { |
39
|
|
|
// Add routes to the route collector. |
40
|
|
|
$dispatcher = \FastRoute\simpleDispatcher( |
41
|
|
|
function (RouteCollector $collector) { |
42
|
|
|
foreach ($this->routes as $route) { |
43
|
|
|
$collector->addRoute( |
44
|
|
|
$route->getRequestType(), |
45
|
|
|
$route->getUri(), |
46
|
|
|
serialize($route) |
47
|
|
|
); |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
// Dispatch the route. |
54
|
|
|
$route_info = $dispatcher->dispatch($request->getMethod(), $request->getUriPath()); |
55
|
|
|
|
56
|
|
|
// Handle the route depending on the response type. |
57
|
|
|
switch ($route_info[0]) { |
58
|
|
|
// Route not found. |
59
|
|
|
case Dispatcher::NOT_FOUND: |
60
|
|
|
|
61
|
|
|
throw new OutOfRangeException("No route matched the given URI."); |
62
|
|
|
|
63
|
|
|
// Method not allowed for the specified route. |
64
|
|
|
case Dispatcher::METHOD_NOT_ALLOWED: |
65
|
|
|
|
66
|
|
|
throw new Exception("Method not allowed."); |
67
|
|
|
|
68
|
|
|
// Route found. |
69
|
|
|
case Dispatcher::FOUND: |
70
|
|
|
|
71
|
|
|
$route = $route_info[1]; |
72
|
|
|
$params = $route_info[2]; |
73
|
|
|
|
74
|
|
|
return new ResolvedRequest($request, unserialize($route), $params); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|