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
|
|
|
|