1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Component\Http; |
4
|
|
|
|
5
|
|
|
use App\Component\Http\Interfaces\IRoutes; |
6
|
|
|
use App\Component\Http\Route; |
7
|
|
|
|
8
|
|
|
class Routes implements IRoutes |
9
|
|
|
{ |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* routes config collection |
13
|
|
|
* |
14
|
|
|
* @var array |
15
|
|
|
*/ |
16
|
|
|
private $routesConfig = []; |
|
|
|
|
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* route list as array |
20
|
|
|
* |
21
|
|
|
* @var array |
22
|
|
|
*/ |
23
|
|
|
private $routes = []; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* __construct |
27
|
|
|
* |
28
|
|
|
* @param array $routesConfig |
29
|
|
|
* @return Routes |
30
|
|
|
*/ |
31
|
5 |
|
public function __construct(array $routesConfig = []) |
32
|
|
|
{ |
33
|
5 |
|
if (!empty($routesConfig)) { |
34
|
5 |
|
$this->set($routesConfig); |
35
|
|
|
} |
36
|
5 |
|
return $this; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* returns routes as array |
41
|
|
|
* |
42
|
|
|
* @return array |
43
|
|
|
*/ |
44
|
1 |
|
public function get(): array |
45
|
|
|
{ |
46
|
1 |
|
return $this->routes; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* returns routes as array |
51
|
|
|
* |
52
|
|
|
* @return array |
53
|
|
|
*/ |
54
|
2 |
|
public function getExpr(): array |
55
|
|
|
{ |
56
|
2 |
|
$patterns = array_map( |
57
|
2 |
|
function (Route $i) { |
58
|
2 |
|
return $i->getExpr(); |
59
|
2 |
|
}, |
60
|
2 |
|
$this->routes |
61
|
|
|
); |
62
|
2 |
|
return $patterns; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* set routes as array and stack Route collection |
67
|
|
|
* |
68
|
|
|
* @param array $routesConfig |
69
|
|
|
* @return Routes |
70
|
|
|
*/ |
71
|
5 |
|
public function set(array $routesConfig): Routes |
72
|
|
|
{ |
73
|
5 |
|
$this->routes = []; |
74
|
5 |
|
$this->prepare($routesConfig); |
75
|
5 |
|
$this->validate(); |
76
|
5 |
|
return $this; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* stacks routes as Route object collection from routes config |
81
|
|
|
* |
82
|
|
|
* @param array $routesConfig |
83
|
|
|
* @return Routes |
84
|
|
|
*/ |
85
|
1 |
|
protected function prepare(array $routesConfig):Routes |
86
|
|
|
{ |
87
|
1 |
|
$count = count($routesConfig); |
88
|
1 |
|
for ($c = 0; $c < $count; $c++) { |
89
|
1 |
|
$this->routes[] = new Route($routesConfig[$c]); |
90
|
|
|
} |
91
|
1 |
|
return $this; |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
/** |
95
|
|
|
* validate routes to be an array of regexp string |
96
|
|
|
* |
97
|
|
|
* @throws Exception |
98
|
|
|
*/ |
99
|
2 |
|
protected function validate() |
100
|
|
|
{ |
101
|
2 |
|
$count = count($this->routes); |
102
|
2 |
|
for ($c = 0; $c < $count; $c++) { |
103
|
2 |
|
$route = $this->routes[$c]->getExpr(); |
104
|
2 |
|
if (@preg_match($route, null) === false) { |
105
|
1 |
|
throw new \Exception('Route invalid expr ' . $route); |
106
|
|
|
} |
107
|
|
|
} |
108
|
|
|
} |
109
|
|
|
} |
110
|
|
|
|