1 | <?php |
||
2 | /** |
||
3 | * Layers manager |
||
4 | * User: moyo |
||
5 | * Date: 19/03/2018 |
||
6 | * Time: 10:51 AM |
||
7 | */ |
||
8 | |||
9 | namespace Carno\Chain\Chips; |
||
10 | |||
11 | use Carno\Chain\Layered; |
||
12 | |||
13 | trait Extensions |
||
14 | { |
||
15 | /** |
||
16 | * @param string $search |
||
17 | * @return bool |
||
18 | */ |
||
19 | public function has(string $search) : bool |
||
20 | { |
||
21 | foreach ($this->layers as $layer) { |
||
22 | if ($this->matched($layer, $search)) { |
||
23 | return true; |
||
24 | } |
||
25 | } |
||
26 | |||
27 | return false; |
||
28 | } |
||
29 | |||
30 | /** |
||
31 | * @param string $search |
||
32 | * @return bool |
||
33 | */ |
||
34 | public function remove(string $search) : bool |
||
35 | { |
||
36 | foreach ($this->layers as $idx => $layer) { |
||
37 | if ($this->matched($layer, $search)) { |
||
38 | unset($this->layers[$idx]); |
||
39 | $this->layers = array_values($this->layers); |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
40 | return true; |
||
41 | } |
||
42 | } |
||
43 | |||
44 | return false; |
||
45 | } |
||
46 | |||
47 | /** |
||
48 | * @param string $offset |
||
49 | * @param Layered ...$layers |
||
50 | * @return bool |
||
51 | */ |
||
52 | public function prepend(string $offset = null, Layered ...$layers) : bool |
||
53 | { |
||
54 | return $this->operating($offset, 'array_unshift', 0, $layers); |
||
55 | } |
||
56 | |||
57 | /** |
||
58 | * @param string $offset |
||
59 | * @param Layered ...$layers |
||
60 | * @return bool |
||
61 | */ |
||
62 | public function append(string $offset = null, Layered ...$layers) : bool |
||
63 | { |
||
64 | return $this->operating($offset, 'array_push', 1, $layers); |
||
65 | } |
||
66 | |||
67 | /** |
||
68 | * @param string $match |
||
69 | * @param string $func1 |
||
70 | * @param int $offset |
||
71 | * @param array $layers |
||
72 | * @return bool |
||
73 | */ |
||
74 | private function operating(?string $match, string $func1, int $offset, array $layers) : bool |
||
75 | { |
||
76 | if (is_null($match)) { |
||
77 | $func1($this->layers, ...$layers); |
||
78 | return true; |
||
79 | } else { |
||
80 | foreach ($this->layers as $idx => $layered) { |
||
81 | if ($this->matched($layered, $match)) { |
||
82 | $this->layers = array_merge( |
||
0 ignored issues
–
show
|
|||
83 | array_slice($this->layers, 0, $idx + $offset), |
||
84 | $layers, |
||
85 | array_slice($this->layers, $idx + $offset) |
||
86 | ); |
||
87 | return true; |
||
88 | } |
||
89 | } |
||
90 | } |
||
91 | |||
92 | return false; |
||
93 | } |
||
94 | |||
95 | /** |
||
96 | * @param Layered $layer |
||
97 | * @param string $api |
||
98 | * @return bool |
||
99 | */ |
||
100 | private function matched(Layered $layer, string $api) : bool |
||
101 | { |
||
102 | return get_class($layer) === $api || in_array($api, class_implements($layer)); |
||
103 | } |
||
104 | } |
||
105 |