| 1 | <?php |
||
| 5 | final class EventSubscriber |
||
| 6 | { |
||
| 7 | private StoredEventRepository $repository; |
||
|
|
|||
| 8 | |||
| 9 | public function __construct(string $storedEventRepository) |
||
| 10 | { |
||
| 11 | $this->repository = app($storedEventRepository); |
||
| 12 | } |
||
| 13 | |||
| 14 | public function subscribe($events): void |
||
| 15 | { |
||
| 16 | $events->listen('*', static::class.'@handle'); |
||
| 17 | } |
||
| 18 | |||
| 19 | public function handle(string $eventName, $payload): void |
||
| 20 | { |
||
| 21 | if (! $this->shouldBeStored($eventName)) { |
||
| 22 | return; |
||
| 23 | } |
||
| 24 | |||
| 25 | $this->storeEvent($payload[0]); |
||
| 26 | } |
||
| 27 | |||
| 28 | public function storeEvent(ShouldBeStored $event): void |
||
| 29 | { |
||
| 30 | $storedEvent = $this->repository->persist($event); |
||
| 31 | $storedEvent->handle(); |
||
| 32 | } |
||
| 33 | |||
| 34 | private function shouldBeStored($event): bool |
||
| 35 | { |
||
| 36 | if (! class_exists($event)) { |
||
| 37 | return false; |
||
| 38 | } |
||
| 39 | |||
| 40 | return is_subclass_of($event, ShouldBeStored::class); |
||
| 41 | } |
||
| 42 | } |
||
| 43 |