Completed
Push — master ( 0ba1f3...e49bb9 )
by Freek
03:02
created

EventSubscriber::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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