1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Remorhaz\JSON\Path\Value; |
5
|
|
|
|
6
|
|
|
use function array_key_exists; |
7
|
|
|
use function array_keys; |
8
|
|
|
use function count; |
9
|
|
|
use function in_array; |
10
|
|
|
|
11
|
|
|
final class IndexMap implements IndexMapInterface |
12
|
|
|
{ |
13
|
|
|
|
14
|
|
|
private $outerIndexes; |
15
|
|
|
|
16
|
28 |
|
public function __construct(?int ...$outerIndexes) |
17
|
|
|
{ |
18
|
28 |
|
$this->outerIndexes = $outerIndexes; |
19
|
28 |
|
} |
20
|
|
|
|
21
|
4 |
|
public function count() |
22
|
|
|
{ |
23
|
4 |
|
return count($this->outerIndexes); |
24
|
|
|
} |
25
|
|
|
|
26
|
8 |
|
public function getInnerIndexes(): array |
27
|
|
|
{ |
28
|
8 |
|
return array_keys($this->outerIndexes); |
29
|
|
|
} |
30
|
|
|
|
31
|
15 |
|
public function getOuterIndexes(): array |
32
|
|
|
{ |
33
|
15 |
|
return $this->outerIndexes; |
34
|
|
|
} |
35
|
|
|
|
36
|
3 |
|
public function getOuterIndex(int $innerIndex): int |
37
|
|
|
{ |
38
|
3 |
|
if (!isset($this->outerIndexes[$innerIndex])) { |
39
|
2 |
|
throw new Exception\OuterIndexNotFoundException($innerIndex, $this); |
40
|
|
|
} |
41
|
|
|
|
42
|
1 |
|
return $this->outerIndexes[$innerIndex]; |
|
|
|
|
43
|
|
|
} |
44
|
|
|
|
45
|
5 |
|
public function outerIndexExists(int $outerIndex): bool |
46
|
|
|
{ |
47
|
5 |
|
return in_array($outerIndex, $this->outerIndexes, true); |
48
|
|
|
} |
49
|
|
|
|
50
|
4 |
|
public function split(): IndexMapInterface |
51
|
|
|
{ |
52
|
4 |
|
return new self(...$this->getInnerIndexes()); |
53
|
|
|
} |
54
|
|
|
|
55
|
4 |
|
public function join(IndexMapInterface $indexMap): IndexMapInterface |
56
|
|
|
{ |
57
|
4 |
|
$outerIndexes = []; |
58
|
4 |
|
foreach ($indexMap->getOuterIndexes() as $innerIndex => $outerIndex) { |
59
|
3 |
|
$outerIndexes[] = $this->outerIndexExists($innerIndex) |
60
|
3 |
|
? $outerIndex |
61
|
1 |
|
: null; |
62
|
|
|
} |
63
|
|
|
|
64
|
4 |
|
return new self(...$outerIndexes); |
65
|
|
|
} |
66
|
|
|
|
67
|
3 |
|
public function equals(IndexMapInterface $indexMap): bool |
68
|
|
|
{ |
69
|
3 |
|
return $this->outerIndexes === $indexMap->getOuterIndexes(); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function isCompatible(IndexMapInterface $indexMap): bool |
73
|
|
|
{ |
74
|
|
|
if (count($indexMap) != count($this)) { |
75
|
|
|
return false; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
$anotherMap = $indexMap->getOuterIndexes(); |
79
|
|
|
foreach ($this->outerIndexes as $innerIndex => $outerIndex) { |
80
|
|
|
if (!array_key_exists($innerIndex, $anotherMap)) { |
81
|
|
|
return false; |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
if (!isset($outerIndex, $anotherMap[$innerIndex])) { |
85
|
|
|
continue; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
if ($outerIndex !== $anotherMap[$innerIndex]) { |
89
|
|
|
return false; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
return true; |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|