Passed
Push — master ( 9e5c60...cc25de )
by Edward
11:49
created

NodeValueListBuilder::valueExists()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 4
nop 2
dl 0
loc 15
ccs 0
cts 0
cp 0
crap 20
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Remorhaz\JSON\Path\Value;
5
6
use Remorhaz\JSON\Data\Value\NodeValueInterface;
7
8
final class NodeValueListBuilder
9
{
10
11
    private $outerIndexes = [];
12
13
    /**
14
     * @var NodeValueInterface[]
15 5
     */
16
    private $values = [];
17 5
18 5
    public function addValue(NodeValueInterface $value, int $outerIndex): self
19
    {
20 5
        if ($this->valueExists($value, $outerIndex)) {
21
            return $this;
22
        }
23 6
24
        $this->outerIndexes[] = $outerIndex;
25 6
        $this->values[] = $value;
26
27
        return $this;
28
    }
29
30
    public function build(): NodeValueListInterface
31
    {
32
        return new NodeValueList(new IndexMap(...$this->outerIndexes), ...$this->values);
33
    }
34
35
    private function valueExists(NodeValueInterface $value, int $outerIndex): bool
36
    {
37
        foreach ($this->values as $innerIndex => $addedValue) {
38
            if (!$addedValue->getPath()->equals($value->getPath())) {
39
                continue;
40
            }
41
            $addedOuterIndex = $this->outerIndexes[$innerIndex];
42
            if ($outerIndex == $addedOuterIndex) {
43
                return true;
44
            }
45
46
            throw new Exception\ValueInListWithAnotherOuterIndexException($value, $addedOuterIndex, $outerIndex);
47
        }
48
49
        return false;
50
    }
51
}
52