-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathFastRouteMiddleware.php
90 lines (71 loc) · 2.57 KB
/
FastRouteMiddleware.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
<?php
declare(strict_types=1);
namespace WoohooLabs\Harmony\Middleware;
use FastRoute\Dispatcher;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use WoohooLabs\Harmony\Exception\FastRouteException;
use WoohooLabs\Harmony\Exception\MethodNotAllowed;
use WoohooLabs\Harmony\Exception\RouteNotFound;
class FastRouteMiddleware implements MiddlewareInterface
{
protected ?Dispatcher $fastRoute;
protected string $actionAttributeName;
public function __construct(?Dispatcher $fastRoute = null, string $actionAttributeName = "__action")
{
$this->fastRoute = $fastRoute;
$this->actionAttributeName = $actionAttributeName;
}
/**
* @throws MethodNotAllowed
* @throws RouteNotFound
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$request = $this->routeRequest($request);
return $handler->handle($request);
}
public function getFastRoute(): Dispatcher
{
if ($this->fastRoute === null) {
throw $this->createFastRouteException();
}
return $this->fastRoute;
}
public function setFastRoute(Dispatcher $fastRoute): void
{
$this->fastRoute = $fastRoute;
}
public function getActionAttributeName(): string
{
return $this->actionAttributeName;
}
public function setActionAttributeName(string $actionAttributeName): void
{
$this->actionAttributeName = $actionAttributeName;
}
protected function routeRequest(ServerRequestInterface $request): ServerRequestInterface
{
if ($this->fastRoute === null) {
throw $this->createFastRouteException();
}
$route = $this->fastRoute->dispatch($request->getMethod(), $request->getUri()->getPath());
if ($route[0] === Dispatcher::NOT_FOUND) {
throw new RouteNotFound($request->getUri()->getPath());
}
if ($route[0] === Dispatcher::METHOD_NOT_ALLOWED) {
throw new MethodNotAllowed($request->getMethod());
}
foreach ($route[2] as $name => $value) {
$request = $request->withAttribute($name, $value);
}
$request = $request->withAttribute($this->actionAttributeName, $route[1]);
return $request;
}
private function createFastRouteException(): FastRouteException
{
return new FastRouteException("Property FastRouteMiddleware::\$fastRoute isn't set!");
}
}