Total Complexity | 21 |
Total Lines | 72 |
Duplicated Lines | 0 % |
Coverage | 0% |
Changes | 1 | ||
Bugs | 0 | Features | 1 |
1 | <?php |
||
9 | final class SliceElementMatcher implements ChildMatcherInterface |
||
10 | { |
||
11 | |||
12 | private $count; |
||
13 | |||
14 | private $start; |
||
15 | |||
16 | private $end; |
||
17 | |||
18 | private $step; |
||
19 | |||
20 | private $isReverse; |
||
21 | |||
22 | public function __construct(int $count, ?int $start, ?int $end, ?int $step) |
||
23 | { |
||
24 | $this->count = $count; |
||
25 | $this->step = $step ?? 1; |
||
26 | $this->isReverse = $step < 0; |
||
27 | |||
28 | $this->start = $start; |
||
29 | $this->end = $end; |
||
30 | } |
||
31 | |||
32 | public function match($address): bool |
||
33 | { |
||
34 | if (0 == $this->step || !is_int($address)) { |
||
35 | return false; |
||
36 | } |
||
37 | $start = $this->detectStart($this->count); |
||
38 | $end = $this->detectEnd($this->count); |
||
39 | |||
40 | return $this->isInRange($address, $start, $end) && $this->isOnStep($address, $start); |
||
41 | } |
||
42 | |||
43 | private function detectStart(int $count): int |
||
44 | { |
||
45 | $start = $this->start; |
||
46 | if (!isset($start)) { |
||
47 | $start = $this->isReverse ? -1 : 0; |
||
48 | } |
||
49 | if ($start < 0) { |
||
50 | $start = max($start + $count, 0); |
||
51 | } |
||
52 | |||
53 | return $start; |
||
54 | } |
||
55 | |||
56 | private function detectEnd(int $count): int |
||
57 | { |
||
58 | $end = $this->end; |
||
59 | if (!isset($end)) { |
||
60 | $end = $this->isReverse ? -$count - 1 : $count; |
||
61 | } |
||
62 | if ($end > $count) { |
||
63 | return $count; |
||
64 | } |
||
65 | |||
66 | return $end < 0 |
||
67 | ? max($end + $count, $this->isReverse ? -1 : 0) |
||
68 | : $end; |
||
69 | } |
||
70 | |||
71 | private function isInRange(int $address, int $start, int $end): bool |
||
72 | { |
||
73 | return $this->isReverse |
||
74 | ? $address <= $start && $address > $end |
||
75 | : $address >= $start && $address < $end; |
||
76 | } |
||
77 | |||
78 | private function isOnStep(int $address, int $start): bool |
||
81 | } |
||
82 | } |
||
83 |