Passed
Push — master ( 3a32e2...77143f )
by Edward
04:21
created

ReplaceMutation::createReplaceEventGenerator()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 15
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 12
c 1
b 0
f 0
nc 8
nop 2
dl 0
loc 15
ccs 0
cts 12
cp 0
crap 72
rs 8.4444
1
<?php
2
declare(strict_types=1);
3
4
namespace Remorhaz\JSON\Pointer\Processor\Mutator;
5
6
use Generator;
7
use Iterator;
8
use Remorhaz\JSON\Data\Event\AfterElementEventInterface;
9
use Remorhaz\JSON\Data\Event\AfterPropertyEventInterface;
10
use Remorhaz\JSON\Data\Event\BeforeArrayEventInterface;
11
use Remorhaz\JSON\Data\Event\BeforeElementEventInterface;
12
use Remorhaz\JSON\Data\Event\BeforeObjectEventInterface;
13
use Remorhaz\JSON\Data\Event\BeforePropertyEventInterface;
14
use Remorhaz\JSON\Data\Event\EventInterface;
15
use Remorhaz\JSON\Data\Event\ScalarEventInterface;
16
use Remorhaz\JSON\Data\Path\PathInterface;
17
use Remorhaz\JSON\Data\Value\NodeValueInterface;
18
use Remorhaz\JSON\Data\Walker\MutationInterface;
19
use Remorhaz\JSON\Data\Walker\ValueWalkerInterface;
20
21
final class ReplaceMutation implements MutationInterface
22
{
23
24
    private $newNode;
25
26
    private $path;
27
28
    public function __construct(NodeValueInterface $newNode, PathInterface $path)
29
    {
30
        $this->newNode = $newNode;
31
        $this->path = $path;
32
    }
33
34
    public function __invoke(EventInterface $event, ValueWalkerInterface $valueWalker): Iterator
35
    {
36
        return $this->createEventGenerator($event, $valueWalker);
37
    }
38
39
    public function reset(): void
40
    {
41
    }
42
43
    private function createEventGenerator(EventInterface $event, ValueWalkerInterface $valueWalker): Generator
44
    {
45
        if ($this->path->equals($event->getPath())) {
46
            yield from $this->createReplaceEventGenerator($event, $valueWalker);
47
48
            return;
49
        }
50
        if (!$this->path->contains($event->getPath())) {
51
            yield $event;
52
        }
53
    }
54
55
    private function createReplaceEventGenerator(EventInterface $event, ValueWalkerInterface $valueWalker): Generator
56
    {
57
        switch (true) {
58
            case $event instanceof BeforeElementEventInterface:
59
            case $event instanceof BeforePropertyEventInterface:
60
            case $event instanceof AfterElementEventInterface:
61
            case $event instanceof AfterPropertyEventInterface:
62
                yield $event;
63
                break;
64
65
            case $event instanceof ScalarEventInterface:
66
            case $event instanceof BeforeArrayEventInterface:
67
            case $event instanceof BeforeObjectEventInterface:
68
                yield from $valueWalker->createEventIterator($this->newNode, $event->getPath());
69
                break;
70
        }
71
    }
72
}
73