|
1
|
|
|
<?php |
|
2
|
|
|
namespace Wandu\Router; |
|
3
|
|
|
|
|
4
|
|
|
use FastRoute\Dispatcher as FastDispatcher; |
|
5
|
|
|
use FastRoute\Dispatcher\GroupCountBased as GCBDispatcher; |
|
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
7
|
|
|
use Wandu\Router\Contracts\Dispatchable; |
|
8
|
|
|
use Wandu\Router\Contracts\LoaderInterface; |
|
9
|
|
|
use Wandu\Router\Contracts\ResponsifierInterface; |
|
10
|
|
|
use Wandu\Router\Exception\MethodNotAllowedException; |
|
11
|
|
|
use Wandu\Router\Exception\RouteNotFoundException; |
|
12
|
|
|
|
|
13
|
|
|
class CompiledRouteCollection implements Dispatchable |
|
14
|
|
|
{ |
|
15
|
|
|
/** @var \Wandu\Router\Route[] */ |
|
16
|
|
|
protected $routeMap = []; |
|
17
|
|
|
|
|
18
|
|
|
/** @var array */ |
|
19
|
|
|
protected $compiledRoutes = []; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* @param array $compiledRoutes |
|
23
|
|
|
* @param array $routeMap |
|
24
|
|
|
*/ |
|
25
|
15 |
|
public function __construct(array $compiledRoutes, array $routeMap) |
|
26
|
|
|
{ |
|
27
|
15 |
|
$this->routeMap = $routeMap; |
|
28
|
15 |
|
$this->compiledRoutes = $compiledRoutes; |
|
29
|
15 |
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* {@inheritdoc} |
|
33
|
|
|
*/ |
|
34
|
15 |
|
public function dispatch( |
|
35
|
|
|
LoaderInterface $loader, |
|
36
|
|
|
ResponsifierInterface $responsifier, |
|
37
|
|
|
ServerRequestInterface $request |
|
38
|
|
|
) { |
|
39
|
15 |
|
$host = $request->getHeaderLine('host'); |
|
40
|
15 |
|
$compiledRoutes = array_key_exists($host, $this->compiledRoutes) |
|
41
|
2 |
|
? $this->compiledRoutes[$host] |
|
42
|
15 |
|
: $this->compiledRoutes['@']; |
|
43
|
|
|
|
|
44
|
15 |
|
$routeInfo = (new GCBDispatcher($compiledRoutes)) |
|
45
|
15 |
|
->dispatch($request->getMethod(), '/' . trim($request->getUri()->getPath(), '/')); |
|
46
|
|
|
|
|
47
|
15 |
|
switch ($routeInfo[0]) { |
|
48
|
15 |
|
case FastDispatcher::NOT_FOUND: |
|
49
|
5 |
|
throw new RouteNotFoundException(); |
|
50
|
15 |
|
case FastDispatcher::METHOD_NOT_ALLOWED: |
|
51
|
8 |
|
throw new MethodNotAllowedException(); |
|
52
|
|
|
} |
|
53
|
15 |
|
$route = $this->routeMap[$routeInfo[1]]; |
|
54
|
15 |
|
foreach ($routeInfo[2] as $key => $value) { |
|
55
|
5 |
|
$request = $request->withAttribute($key, $value); |
|
56
|
|
|
} |
|
57
|
15 |
|
$executor = new RouteExecutor($loader, $responsifier); |
|
58
|
15 |
|
return $executor->execute($route, $request); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|