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