1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SimpleRoute; |
4
|
|
|
|
5
|
|
|
use FastRoute; |
6
|
|
|
use FastRoute\Dispatcher; |
7
|
|
|
use FastRoute\RouteCollector; |
8
|
|
|
use SimpleRoute\Exception\MethodNotAllowedException; |
9
|
|
|
use SimpleRoute\Exception\NotFoundException; |
10
|
|
|
|
11
|
|
|
final class Router implements RouterInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var Dispatcher |
15
|
|
|
*/ |
16
|
|
|
private $dispatcher; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var RouteInterface[] |
20
|
|
|
*/ |
21
|
|
|
private $routes; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* This method is not part of the public API. Implementations should use |
25
|
|
|
* Router::fromArray(). |
26
|
|
|
* |
27
|
|
|
* @param RouteInterface[] A collection of routes |
28
|
|
|
*/ |
29
|
15 |
|
public function __construct(array $routes) |
30
|
|
|
{ |
31
|
15 |
|
$this->routes = array(); |
32
|
|
|
|
33
|
15 |
|
$this->dispatcher = FastRoute\simpleDispatcher(function (RouteCollector $collector) use ($routes) { |
34
|
15 |
|
foreach ($routes as $route) { |
35
|
12 |
|
if (!$route instanceof RouteInterface) { |
36
|
3 |
|
throw new \InvalidArgumentException('Routes array must contain only RouteInterface objects'); |
37
|
|
|
} |
38
|
|
|
|
39
|
9 |
|
$key = spl_object_hash($route); |
40
|
|
|
|
41
|
9 |
|
$this->routes[$key] = $route; |
42
|
|
|
|
43
|
9 |
|
$collector->addRoute($route->getMethods(), $route->getPattern(), $key); |
44
|
12 |
|
} |
45
|
15 |
|
}); |
46
|
12 |
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param RouteInterface[] A collection of routes |
50
|
|
|
* @return self |
51
|
|
|
*/ |
52
|
15 |
|
public static function fromArray(array $routes) |
53
|
|
|
{ |
54
|
15 |
|
return new self($routes); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* {@inheritdoc} |
59
|
|
|
*/ |
60
|
12 |
|
public function match($method, $uri) |
61
|
|
|
{ |
62
|
12 |
|
$routeInfo = $this->dispatcher->dispatch($method, $uri); |
63
|
|
|
|
64
|
12 |
|
switch ($routeInfo[0]) { |
65
|
12 |
|
case Dispatcher::METHOD_NOT_ALLOWED: |
66
|
3 |
|
throw new MethodNotAllowedException($method, $routeInfo[1]); |
67
|
9 |
|
case Dispatcher::NOT_FOUND: |
68
|
3 |
|
throw new NotFoundException($uri); |
69
|
6 |
|
} |
70
|
|
|
|
71
|
6 |
|
return new Result($this->routes[$routeInfo[1]], $routeInfo[2]); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|