1 | <?php |
||
2 | |||
3 | namespace Bavix\Router; |
||
4 | |||
5 | use Bavix\Exceptions; |
||
6 | use Bavix\Slice\Slice; |
||
7 | use Psr\Cache\CacheItemPoolInterface; |
||
8 | |||
9 | class Configure |
||
10 | { |
||
11 | |||
12 | use HelperThrows; |
||
13 | |||
14 | /** |
||
15 | * @var CacheItemPoolInterface |
||
16 | */ |
||
17 | protected $pool; |
||
18 | |||
19 | /** |
||
20 | * @var Slice |
||
21 | */ |
||
22 | protected $slice; |
||
23 | |||
24 | /** |
||
25 | * @var Slice |
||
26 | */ |
||
27 | protected $build; |
||
28 | |||
29 | /** |
||
30 | * Configure constructor. |
||
31 | * |
||
32 | * @param array|\Traversable|Slice $data |
||
33 | * @param CacheItemPoolInterface|null $pool |
||
34 | */ |
||
35 | 5 | public function __construct($data, CacheItemPoolInterface $pool = null) |
|
36 | { |
||
37 | 5 | $this->slice = Slice::from($data); |
|
38 | 5 | $this->pool = $pool; |
|
39 | |||
40 | 5 | $this->types = [ |
|
41 | 'http' => Type\Http::class, |
||
42 | 'prefix' => Type\Prefix::class, |
||
43 | 'pattern' => Type\Pattern::class, |
||
44 | ]; |
||
45 | 5 | } |
|
46 | |||
47 | /** |
||
48 | * @return Slice |
||
49 | * |
||
50 | * @return Slice |
||
51 | * @throws \Psr\Cache\InvalidArgumentException |
||
52 | */ |
||
53 | 5 | public function data(): Slice |
|
54 | { |
||
55 | 5 | if ($this->pool instanceof CacheItemPoolInterface) |
|
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
56 | { |
||
57 | $item = $this->pool->getItem($this->slice); |
||
58 | |||
59 | if (!$item->isHit()) |
||
60 | { |
||
61 | $item->set($result = $this->build()); |
||
62 | $this->pool->save($item); |
||
63 | |||
64 | return $result; |
||
65 | } |
||
66 | |||
67 | return $item->get(); |
||
68 | } |
||
69 | |||
70 | 5 | return $this->build(); |
|
71 | } |
||
72 | |||
73 | /** |
||
74 | * @return Route[] |
||
75 | * |
||
76 | * @throws Exceptions\NotFound\Data |
||
77 | */ |
||
78 | 5 | protected function routes(): array |
|
79 | { |
||
80 | 5 | $routes = []; |
|
81 | |||
82 | 5 | foreach ($this->slice->asGenerator() as $key => $slice) |
|
83 | { |
||
84 | 5 | if ($key{0} === '@') |
|
85 | { |
||
86 | // for xml |
||
87 | continue; |
||
88 | } |
||
89 | |||
90 | 5 | $type = $this->getType($slice, $key); |
|
91 | 4 | $class = $this->types[$type]; |
|
92 | |||
93 | /** |
||
94 | * @var $object Type |
||
95 | */ |
||
96 | 4 | $object = new $class($this, $slice, [ |
|
97 | 4 | 'key' => $key |
|
98 | ]); |
||
99 | |||
100 | 3 | $routes += $object->build(); |
|
101 | } |
||
102 | |||
103 | 3 | return $routes; |
|
104 | } |
||
105 | |||
106 | /** |
||
107 | * @return Slice |
||
108 | */ |
||
109 | 5 | public function build(): Slice |
|
110 | { |
||
111 | 5 | if (!$this->build) |
|
112 | { |
||
113 | 5 | $this->build = $this->slice->make( |
|
114 | 5 | $this->routes() |
|
115 | ); |
||
116 | } |
||
117 | |||
118 | 3 | return $this->build; |
|
119 | } |
||
120 | |||
121 | } |
||
122 |