This repository has been archived by the owner on Apr 13, 2021. It is now read-only.
forked from jicjjang/June
-
Notifications
You must be signed in to change notification settings - Fork 2
/
CompiledRouteCollection.php
60 lines (53 loc) · 1.93 KB
/
CompiledRouteCollection.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
<?php
namespace Wandu\Router;
use FastRoute\Dispatcher as FastDispatcher;
use FastRoute\Dispatcher\GroupCountBased as GCBDispatcher;
use Psr\Http\Message\ServerRequestInterface;
use Wandu\Router\Contracts\Dispatchable;
use Wandu\Router\Contracts\LoaderInterface;
use Wandu\Router\Contracts\ResponsifierInterface;
use Wandu\Router\Exception\MethodNotAllowedException;
use Wandu\Router\Exception\RouteNotFoundException;
class CompiledRouteCollection implements Dispatchable
{
/** @var \Wandu\Router\Route[] */
protected $routeMap = [];
/** @var array */
protected $compiledRoutes = [];
/**
* @param array $compiledRoutes
* @param array $routeMap
*/
public function __construct(array $compiledRoutes, array $routeMap)
{
$this->routeMap = $routeMap;
$this->compiledRoutes = $compiledRoutes;
}
/**
* {@inheritdoc}
*/
public function dispatch(
LoaderInterface $loader,
ResponsifierInterface $responsifier,
ServerRequestInterface $request
) {
$host = $request->getHeaderLine('host');
$compiledRoutes = array_key_exists($host, $this->compiledRoutes)
? $this->compiledRoutes[$host]
: $this->compiledRoutes['@'];
$routeInfo = (new GCBDispatcher($compiledRoutes))
->dispatch($request->getMethod(), '/' . trim($request->getUri()->getPath(), '/'));
switch ($routeInfo[0]) {
case FastDispatcher::NOT_FOUND:
throw new RouteNotFoundException();
case FastDispatcher::METHOD_NOT_ALLOWED:
throw new MethodNotAllowedException();
}
$route = $this->routeMap[$routeInfo[1]];
foreach ($routeInfo[2] as $key => $value) {
$request = $request->withAttribute($key, $value);
}
$executor = new RouteExecutor($loader, $responsifier);
return $executor->execute($route, $request);
}
}