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