Skip to content

Commit 70cf60c

Browse files
committed
added event dispatcher for child entities inside elastic entity
- iterates child entities and dispatches events on them
1 parent 87495af commit 70cf60c

2 files changed

Lines changed: 83 additions & 0 deletions

File tree

src/Config/Elastic.neon

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ services:
3535
delete:
3636
factory: Spameri\Elastic\Model\Delete
3737

38+
dispatchEvents:
39+
factory: Spameri\Elastic\EventManager\DispatchEvents
40+
3841
aggregate:
3942
factory: Spameri\Elastic\Model\Aggregate
4043

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Spameri\Elastic\EventManager;
4+
5+
readonly class DispatchEvents
6+
{
7+
8+
public function __construct(
9+
private \Spameri\Elastic\EventManager $eventManager,
10+
private \Spameri\Elastic\Model\ChangeSet $changeSet,
11+
)
12+
{
13+
}
14+
15+
16+
public function execute(
17+
\Spameri\Elastic\Entity\AbstractElasticEntity $entity,
18+
string $eventType,
19+
): void
20+
{
21+
$this->iterateVariables(
22+
variables: $entity->entityVariables(),
23+
eventType: $eventType,
24+
parent: $entity,
25+
);
26+
}
27+
28+
29+
public function iterateVariables(
30+
array $variables,
31+
string $eventType,
32+
\Spameri\Elastic\Entity\AbstractElasticEntity|\Spameri\Elastic\Entity\EntityInterface $parent,
33+
): void
34+
{
35+
foreach ($variables as $property) {
36+
if ($property instanceof \Spameri\Elastic\Entity\EntityInterface) {
37+
$this->dispatch($eventType, $property, $parent);
38+
39+
} elseif ($property instanceof \Spameri\Elastic\Entity\EntityCollectionInterface) {
40+
/** @var \Spameri\Elastic\Entity\EntityInterface $item */
41+
foreach ($property as $item) {
42+
$this->dispatch($eventType, $item, $parent);
43+
}
44+
}
45+
}
46+
47+
}
48+
49+
50+
public function dispatch(
51+
string $eventType,
52+
\Spameri\Elastic\Entity\EntityInterface $property,
53+
\Spameri\Elastic\Entity\AbstractElasticEntity|\Spameri\Elastic\Entity\EntityInterface $parent,
54+
): void
55+
{
56+
if (
57+
$eventType !== \Spameri\Elastic\EventManager::POST_CREATE
58+
) {
59+
$this->eventManager->dispatch(
60+
event: $eventType,
61+
entityClass: $property::class,
62+
entity: $property,
63+
parent: $parent,
64+
);
65+
66+
} elseif (
67+
$this->changeSet->isExisting($property) === false
68+
) {
69+
$this->eventManager->dispatch(
70+
event: $eventType,
71+
entityClass: $property::class,
72+
entity: $property,
73+
parent: $parent,
74+
);
75+
}
76+
77+
$this->iterateVariables($property->entityVariables(), $eventType, $property);
78+
}
79+
80+
}

0 commit comments

Comments
 (0)