-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFastRouteRouter.php
More file actions
93 lines (80 loc) · 2.66 KB
/
FastRouteRouter.php
File metadata and controls
93 lines (80 loc) · 2.66 KB
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
<?php
declare(strict_types=1);
namespace Lit\Router\FastRoute;
use FastRoute\Dispatcher;
use Lit\Nimo\Handlers\CallableHandler;
use Lit\Router\FastRoute\ArgumentHandler\ArgumentHandlerInterface;
use Lit\Router\FastRoute\ArgumentHandler\RouteArgumentBag;
use Lit\Voltage\AbstractRouter;
use Lit\Voltage\Interfaces\RouterStubResolverInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
/**
* Router use FastRoute to locate stub.
*/
class FastRouteRouter extends AbstractRouter
{
/**
* @var Dispatcher
*/
protected $dispatcher;
/**
* @var mixed
*/
protected $methodNotAllowed;
/**
* @var ArgumentHandlerInterface
*/
protected $argumentHandler;
public function __construct(
Dispatcher $dispatcher,
RouterStubResolverInterface $stubResolver,
ArgumentHandlerInterface $argumentHandler = null,
$notFound = null,
$methodNotAllowed = null
) {
parent::__construct($stubResolver, $notFound);
$this->dispatcher = $dispatcher;
$this->methodNotAllowed = $methodNotAllowed;
$this->argumentHandler = $argumentHandler ?: new RouteArgumentBag();
}
protected function findStub(ServerRequestInterface $request)
{
$path = $request->getUri()->getPath();
$method = $request->getMethod();
$routeInfo = $this->dispatcher->dispatch($method, $path);
return $this->parseRouteInfo($routeInfo);
}
protected function parseRouteInfo($routeInfo)
{
switch ($routeInfo[0]) {
case Dispatcher::NOT_FOUND:
return $this->notFound;
case Dispatcher::METHOD_NOT_ALLOWED:
if (!empty($this->methodNotAllowed)) {
return [$this->methodNotAllowed, [$routeInfo[1]]];
} else {
return $this->notFound;
}
case Dispatcher::FOUND:
list(, $stub, $vars) = $routeInfo;
if (empty($vars)) {
return $stub;
} else {
return $this->proxy($stub, $vars);
}
default:
throw new \Exception(__METHOD__ . '/' . __LINE__);
}
}
protected function proxy($stub, array $vars)
{
$handle = function (ServerRequestInterface $request) use ($stub, $vars): ResponseInterface {
$handler = $this->resolve($stub);
$request = $this->argumentHandler->attachArguments($request, $vars);
$response = $handler->handle($request);
return $response;
};
return CallableHandler::wrap($handle);
}
}