Completed
Push — master ( f318b1...b9f34b )
by Freek
05:03 queued 43s
created

EventHandlerCollection::all()   A

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 0
1
<?php
2
3
namespace Spatie\EventProjector\EventHandlers;
4
5
use Exception;
6
use Illuminate\Support\Collection;
7
use Spatie\EventProjector\EventHandlers\EventHandler;
8
use Spatie\EventProjector\Events\EventHandlerFailedHandlingEvent;
9
use Spatie\EventProjector\Exceptions\InvalidEventHandler;
10
use Spatie\EventProjector\Models\StoredEvent;
11
12
class EventHandlerCollection
13
{
14
    /** @var \Illuminate\Support\Collection */
15
    protected $eventHandlers;
16
17
    public function __construct()
18
    {
19
        $this->eventHandlers = collect();
20
    }
21
22
    public function add(EventHandler $eventHandler)
23
    {
24
        $className = get_class($eventHandler);
25
26
        if (! $this->eventHandlers->has($className)) {
27
            $this->eventHandlers[$className] = $eventHandler;
28
        }
29
    }
30
31
    public function all(): Collection
32
    {
33
        return $this->eventHandlers;
34
    }
35
36
    public function forEvent(StoredEvent $storedEvent): Collection
37
    {
38
        return $this->eventHandlers->filter(function (EventHandler $eventHandler) use ($storedEvent) {
39
            return $eventHandler->handles()->contains($storedEvent->event_class);
40
        });
41
    }
42
43
    public function call(string $method)
44
    {
45
        $this->eventHandlers
46
            ->filter(function (EventHandler $eventHandler) use ($method) {
47
                return method_exists($eventHandler, $method);
48
            })
49
            ->each(function (EventHandler $eventHandler) use ($method) {
50
                return app()->call([$eventHandler, $method]);
51
            });
52
    }
53
}
54