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