AppendElementMutation   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 32
c 1
b 0
f 0
dl 0
loc 63
ccs 0
cts 32
cp 0
rs 10
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A reset() 0 3 1
A __construct() 0 5 1
A __invoke() 0 27 5
A parentPathMatches() 0 11 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Remorhaz\JSON\Pointer\Processor\Mutator;
6
7
use Iterator;
8
use Remorhaz\JSON\Data\Event\AfterArrayEventInterface;
9
use Remorhaz\JSON\Data\Event\AfterElementEvent;
10
use Remorhaz\JSON\Data\Event\BeforeElementEvent;
11
use Remorhaz\JSON\Data\Event\EventInterface;
12
use Remorhaz\JSON\Data\Path\PathInterface;
13
use Remorhaz\JSON\Data\Value\NodeValueInterface;
14
use Remorhaz\JSON\Data\Walker\MutationInterface;
15
use Remorhaz\JSON\Data\Walker\ValueWalkerInterface;
16
17
final class AppendElementMutation implements MutationInterface
18
{
19
20
    private $value;
21
22
    private $path;
23
24
    private $elementIndex;
25
26
    private $elementCounter = 0;
27
28
    public function __construct(NodeValueInterface $value, PathInterface $path, ?int $elementIndex = null)
29
    {
30
        $this->value = $value;
31
        $this->path = $path;
32
        $this->elementIndex = $elementIndex;
33
    }
34
35
    public function __invoke(EventInterface $event, ValueWalkerInterface $valueWalker): Iterator
36
    {
37
        if ($this->parentPathMatches($event)) {
38
            if ($event instanceof AfterElementEvent) {
39
                $this->elementCounter++;
40
            }
41
            yield $event;
42
43
            return;
44
        }
45
46
        if (!$event->getPath()->equals($this->path)) {
47
            yield $event;
48
49
            return;
50
        }
51
52
        if ($event instanceof AfterArrayEventInterface) {
53
            $elementPath = $this
54
                ->path
55
                ->copyWithElement($this->elementCounter);
56
            yield new BeforeElementEvent($this->elementCounter, $elementPath);
57
            yield from $valueWalker->createEventIterator($this->value, $elementPath);
58
            yield new AfterElementEvent($this->elementCounter, $elementPath);
59
        }
60
61
        yield $event;
62
    }
63
64
    public function reset(): void
65
    {
66
        $this->elementCounter = 0;
67
    }
68
69
    private function parentPathMatches(EventInterface $event): bool
70
    {
71
        $pathElements = $event->getPath()->getElements();
72
        if (empty($pathElements)) {
73
            return false;
74
        }
75
76
        return $event
77
            ->getPath()
78
            ->copyParent()
79
            ->equals($this->path);
80
    }
81
}
82