1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Psr7Middlewares\Middleware; |
4
|
|
|
|
5
|
|
|
use Psr7Middlewares\Utils; |
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
7
|
|
|
use Psr\Http\Message\ResponseInterface; |
8
|
|
|
use FastRoute\Dispatcher; |
9
|
|
|
|
10
|
|
|
class FastRoute |
11
|
|
|
{ |
12
|
|
|
use Utils\CallableTrait; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var Dispatcher|null FastRoute dispatcher |
16
|
|
|
*/ |
17
|
|
|
private $router; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Constructor. Set Dispatcher instance. |
21
|
|
|
* |
22
|
|
|
* @param Dispatcher|null $router |
23
|
|
|
*/ |
24
|
|
|
public function __construct(Dispatcher $router = null) |
25
|
|
|
{ |
26
|
|
|
if ($router !== null) { |
27
|
|
|
$this->router($router); |
28
|
|
|
} |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Extra arguments passed to the controller. |
33
|
|
|
* |
34
|
|
|
* @param Dispatcher $router |
35
|
|
|
* |
36
|
|
|
* @return self |
37
|
|
|
*/ |
38
|
|
|
public function router(Dispatcher $router) |
39
|
|
|
{ |
40
|
|
|
$this->router = $router; |
41
|
|
|
|
42
|
|
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Execute the middleware. |
47
|
|
|
* |
48
|
|
|
* @param ServerRequestInterface $request |
49
|
|
|
* @param ResponseInterface $response |
50
|
|
|
* @param callable $next |
51
|
|
|
* |
52
|
|
|
* @return ResponseInterface |
53
|
|
|
*/ |
54
|
|
|
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
55
|
|
|
{ |
56
|
|
|
$route = $this->router->dispatch($request->getMethod(), $request->getUri()->getPath()); |
57
|
|
|
|
58
|
|
|
if ($route[0] === Dispatcher::NOT_FOUND) { |
59
|
|
|
return $response->withStatus(404); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
if ($route[0] === Dispatcher::METHOD_NOT_ALLOWED) { |
63
|
|
|
return $response->withStatus(405); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
foreach ($route[2] as $name => $value) { |
67
|
|
|
$request = $request->withAttribute($name, $value); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
$response = $this->executeCallable($route[1], $request, $response); |
71
|
|
|
|
72
|
|
|
return $next($request, $response); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|