1
|
|
|
<?php |
2
|
|
|
namespace nebula\component\route; |
3
|
|
|
|
4
|
|
|
use Iterator; |
5
|
|
|
use ArrayIterator; |
6
|
|
|
use IteratorAggregate; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* 路由集合 |
10
|
|
|
* |
11
|
|
|
*/ |
12
|
|
|
class RouteCollection implements IteratorAggregate |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* 属性 |
16
|
|
|
* |
17
|
|
|
* @var RouteMatcher[] |
18
|
|
|
*/ |
19
|
|
|
protected $collection = []; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* 创建集合 |
23
|
|
|
* |
24
|
|
|
* @param RouteMatcher[] $collection |
25
|
|
|
*/ |
26
|
|
|
public function __construct(array $collection=[]) |
27
|
|
|
{ |
28
|
|
|
$this->mergeArray($collection); |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* 合并集合 |
33
|
|
|
* |
34
|
|
|
* @param array $collection |
35
|
|
|
* @return void |
36
|
|
|
*/ |
37
|
|
|
public function mergeArray(array $collection=[]) |
38
|
|
|
{ |
39
|
|
|
$this->collection = array_merge($this->collection, $collection); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* 合并 |
44
|
|
|
* |
45
|
|
|
* @param array $route |
46
|
|
|
* @return void |
47
|
|
|
*/ |
48
|
|
|
public function merge(RouteCollection $route) |
49
|
|
|
{ |
50
|
|
|
$this->collection = array_merge($this->collection, $route->collection); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* 添加集合 |
55
|
|
|
* |
56
|
|
|
* @param string $name |
57
|
|
|
* @param RouteMatcher $collection |
58
|
|
|
* @return void |
59
|
|
|
*/ |
60
|
|
|
public function add(string $name, RouteMatcher $collection) |
61
|
|
|
{ |
62
|
|
|
$this->collection[$name] = $collection; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* 获取集合 |
67
|
|
|
* |
68
|
|
|
* @param string $name |
69
|
|
|
* @return RouteMatcher|null |
70
|
|
|
*/ |
71
|
|
|
public function get(string $name):?RouteMatcher |
72
|
|
|
{ |
73
|
|
|
return $this->collection[$name] ?? null; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* 获取迭代器 |
78
|
|
|
* |
79
|
|
|
* @return RouteMatcher[] |
80
|
|
|
*/ |
81
|
|
|
public function getCollection():array |
82
|
|
|
{ |
83
|
|
|
return $this->collection; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* 从文件创建 |
88
|
|
|
* |
89
|
|
|
* @param string $path |
90
|
|
|
* @return self |
91
|
|
|
*/ |
92
|
|
|
public static function fromFile(string $path) |
93
|
|
|
{ |
94
|
|
|
$collection = \unserialize(\file_get_contents($path)); |
95
|
|
|
return new static($collection); |
96
|
|
|
} |
97
|
|
|
|
98
|
|
|
/** |
99
|
|
|
* 保存到文件 |
100
|
|
|
* |
101
|
|
|
* @param string $path |
102
|
|
|
* @return boolean |
103
|
|
|
*/ |
104
|
|
|
public function save(string $path):bool |
105
|
|
|
{ |
106
|
|
|
return \file_put_contents($path, \serialize($this->collection)) > 0; |
107
|
|
|
} |
108
|
|
|
|
109
|
|
|
public function getIterator():Iterator |
110
|
|
|
{ |
111
|
|
|
return new ArrayIterator($this->collection); |
112
|
|
|
} |
113
|
|
|
} |
114
|
|
|
|