1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Mosaic\Routing\Adapters\FastRoute; |
4
|
|
|
|
5
|
|
|
use FastRoute\Dispatcher; |
6
|
|
|
use FastRoute\RouteCollector; |
7
|
|
|
use Mosaic\Routing\Dispatchers\Dispatcher as DispatcherInterface; |
8
|
|
|
use Mosaic\Routing\Exceptions\MethodNotAllowedException; |
9
|
|
|
use Mosaic\Routing\Exceptions\NotFoundHttpException; |
10
|
|
|
use Mosaic\Routing\RouteCollection; |
11
|
|
|
use Mosaic\Routing\RouteDispatcher as RouteDispatcherInterface; |
12
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
13
|
|
|
|
14
|
|
|
class RouteDispatcher implements RouteDispatcherInterface |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var RouteCollection |
18
|
|
|
*/ |
19
|
|
|
private $collection; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var DispatcherInterface |
23
|
|
|
*/ |
24
|
|
|
private $dispatcher; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param DispatcherInterface $dispatcher |
28
|
|
|
* @param RouteCollection $collection |
29
|
|
|
*/ |
30
|
4 |
|
public function __construct(DispatcherInterface $dispatcher, RouteCollection $collection) |
31
|
|
|
{ |
32
|
4 |
|
$this->collection = $collection; |
33
|
4 |
|
$this->dispatcher = $dispatcher; |
34
|
4 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Dispatch the request |
38
|
|
|
* |
39
|
|
|
* @param ServerRequestInterface $request |
40
|
|
|
* @throws MethodNotAllowedException |
41
|
|
|
* @throws NotFoundHttpException |
42
|
|
|
* @return mixed |
43
|
|
|
*/ |
44
|
4 |
|
public function dispatch(ServerRequestInterface $request) |
45
|
|
|
{ |
46
|
4 |
|
$method = $request->getMethod(); |
47
|
4 |
|
$uri = $request->getUri()->getPath(); |
48
|
|
|
|
49
|
4 |
|
$routeInfo = $this->createDispatcher()->dispatch($method, $uri); |
50
|
|
|
|
51
|
4 |
|
switch ($routeInfo[0]) { |
52
|
4 |
|
case Dispatcher::NOT_FOUND: |
53
|
1 |
|
throw new NotFoundHttpException; |
54
|
|
|
|
55
|
3 |
|
case Dispatcher::METHOD_NOT_ALLOWED: |
56
|
1 |
|
throw new MethodNotAllowedException($routeInfo[1]); |
57
|
|
|
|
58
|
2 |
|
case Dispatcher::FOUND: |
59
|
2 |
|
$route = $routeInfo[1]; |
60
|
2 |
|
$route->bind($routeInfo[2]); |
61
|
|
|
|
62
|
|
|
return $this->dispatcher->dispatch($route, function ($response) { |
63
|
|
|
return $response; |
64
|
2 |
|
}); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @return Dispatcher |
70
|
|
|
*/ |
71
|
|
|
private function createDispatcher() |
72
|
|
|
{ |
73
|
4 |
|
return \FastRoute\simpleDispatcher(function (RouteCollector $collector) { |
74
|
4 |
|
foreach ($this->collection as $route) { |
75
|
3 |
|
$collector->addRoute($route->methods(), $route->uri(), $route); |
76
|
|
|
} |
77
|
4 |
|
}); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|