Completed
Push — master ( ebed30...ed4555 )
by Edward
04:50
created

IndexMap::isCompatible()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 6
nop 1
dl 0
loc 22
ccs 0
cts 12
cp 0
crap 42
rs 9.2222
c 0
b 0
f 0
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
10
final class IndexMap implements IndexMapInterface
11
{
12
13
    private $map;
14
15
    public function __construct(?int ...$map)
16
    {
17
        $this->map = $map;
18
    }
19
20
    public function count()
21
    {
22
        return count($this->map);
23
    }
24
25
    public function getInnerIndice(): array
26
    {
27
        return array_keys($this->map);
28
    }
29
30
    public function toArray(): array
31
    {
32
        return $this->map;
33
    }
34
35
    public function getOuterIndex(int $innerIndex): int
36
    {
37
        if (!isset($this->map[$innerIndex])) {
38
            throw new Exception\OuterIndexNotFoundException($innerIndex, $this);
39
        }
40
41
        return $this->map[$innerIndex];
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->map[$innerIndex] could return the type null which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
42
    }
43
44
    public function outerIndexExists(int $outerIndex): bool
45
    {
46
        return in_array($outerIndex, $this->map, true);
47
    }
48
49
    public function split(): IndexMapInterface
50
    {
51
        return new self(...array_keys($this->map));
52
    }
53
54
    public function join(IndexMapInterface $indexMap): IndexMapInterface
55
    {
56
        $map = [];
57
        foreach ($indexMap->toArray() as $innerIndex => $outerIndex) {
58
            $map[] = \in_array($innerIndex, $this->map)
59
                ? $outerIndex
60
                : null;
61
        }
62
63
        return new self(...$map);
64
    }
65
66
    public function equals(IndexMapInterface $indexMap): bool
67
    {
68
        return $this->map === $indexMap->toArray();
69
    }
70
71
    public function isCompatible(IndexMapInterface $indexMap): bool
72
    {
73
        if (count($indexMap) != count($this)) {
74
            return false;
75
        }
76
77
        $anotherMap = $indexMap->toArray();
78
        foreach ($this->map as $innerIndex => $outerIndex) {
79
            if (!array_key_exists($innerIndex, $anotherMap)) {
80
                return false;
81
            }
82
83
            if (!isset($outerIndex, $anotherMap[$innerIndex])) {
84
                continue;
85
            }
86
87
            if ($outerIndex !== $anotherMap[$innerIndex]) {
88
                return false;
89
            }
90
        }
91
92
        return true;
93
    }
94
}
95