|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Piface\Router; |
|
4
|
|
|
|
|
5
|
|
|
use Piface\Router\Exception\DuplicateRouteNameException; |
|
6
|
|
|
use Piface\Router\Exception\DuplicateRouteUriException; |
|
7
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
8
|
|
|
|
|
9
|
|
|
class RouterContainer |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* Array of route objects |
|
13
|
|
|
* |
|
14
|
|
|
* @var Route[] |
|
15
|
|
|
*/ |
|
16
|
|
|
private $routes = []; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* index all routes which have been registered to avoid duplication. |
|
20
|
|
|
* |
|
21
|
|
|
* @var array |
|
22
|
|
|
*/ |
|
23
|
|
|
private $path = []; |
|
24
|
|
|
|
|
25
|
|
|
public function addRoute(Route $route): Route |
|
26
|
|
|
{ |
|
27
|
|
|
if (\in_array($route->getPath(), $this->path, true)) { |
|
28
|
|
|
throw new DuplicateRouteUriException($route->getPath()); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
if (array_key_exists($route->getName(), $this->path)) { |
|
32
|
|
|
throw new DuplicateRouteNameException($route->getName()); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
$this->path[$route->getName()] = $route->getPath(); |
|
36
|
|
|
$this->routes[$route->getName()] = $route; |
|
37
|
|
|
|
|
38
|
|
|
return $route; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Check if the current object route is matching the request route. |
|
43
|
|
|
*/ |
|
44
|
|
|
public function match(ServerRequestInterface $request, Route $route): bool |
|
45
|
|
|
{ |
|
46
|
|
|
$requestedPath = $request->getUri()->getPath(); |
|
47
|
|
|
$path = $this->generatePath($route); |
|
48
|
|
|
|
|
49
|
|
|
if (!preg_match("#^$path$#i", $requestedPath, $matches)) { |
|
50
|
|
|
return false; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
array_shift($matches); |
|
54
|
|
|
$route->setParameters($matches); |
|
55
|
|
|
|
|
56
|
|
|
return true; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* @return Route[] |
|
61
|
|
|
*/ |
|
62
|
|
|
public function getRoutes(): array |
|
63
|
|
|
{ |
|
64
|
|
|
return $this->routes; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
private function generatePath(Route $route): string |
|
68
|
|
|
{ |
|
69
|
|
|
$path = $route->getPath(); |
|
70
|
|
|
|
|
71
|
|
|
if (!empty($route->getWhere())) { |
|
72
|
|
|
foreach ($route->getWhere() as $attribute => $where) { |
|
73
|
|
|
$path = preg_replace('#{(' . $attribute . ')}#', '(' . $where . ')', $path); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
$path = preg_replace("#{([\w]+)}#", '([^/]+)', $path); |
|
77
|
|
|
|
|
78
|
|
|
return $path; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|