EventSubscriber::subscribe()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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