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

AppendPropertyMutation::__invoke()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace Remorhaz\JSON\Pointer\Processor\Mutator;
5
6
use Generator;
7
use Remorhaz\JSON\Data\Event\AfterObjectEventInterface;
8
use Remorhaz\JSON\Data\Event\AfterPropertyEvent;
9
use Remorhaz\JSON\Data\Event\BeforePropertyEvent;
10
use Remorhaz\JSON\Data\Event\EventInterface;
11
use Remorhaz\JSON\Data\Path\PathInterface;
12
use Remorhaz\JSON\Data\Value\NodeValueInterface;
13
use Remorhaz\JSON\Data\Walker\MutationInterface;
14
use Remorhaz\JSON\Data\Walker\ValueWalkerInterface;
15
16
final class AppendPropertyMutation implements MutationInterface
17
{
18
19
    private $value;
20
21
    private $path;
22
23
    private $propertyName;
24
25
    public function __construct(NodeValueInterface $value, PathInterface $path, string $propertyName)
26
    {
27
        $this->value = $value;
28
        $this->path = $path;
29
        $this->propertyName = $propertyName;
30
    }
31
32
    public function __invoke(EventInterface $event, ValueWalkerInterface $valueWalker)
33
    {
34
        return $this->createEventGenerator($event, $valueWalker);
35
    }
36
37
    public function reset(): void
38
    {
39
    }
40
41
    private function createEventGenerator(EventInterface $event, ValueWalkerInterface $valueWalker): Generator
42
    {
43
        if (!$this->path->equals($event->getPath())) {
44
            yield $event;
45
46
            return;
47
        }
48
49
        if ($event instanceof AfterObjectEventInterface) {
50
            $propertyPath = $this->path->copyWithProperty($this->propertyName);
51
            yield new BeforePropertyEvent($this->propertyName, $propertyPath);
52
            yield from $valueWalker->createEventIterator($this->value, $propertyPath);
53
            yield new AfterPropertyEvent($this->propertyName, $propertyPath);
54
        }
55
56
        yield $event;
57
    }
58
}
59