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

EventHandlerCollection   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 2
dl 0
loc 42
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A add() 0 8 2
A all() 0 4 1
A forEvent() 0 6 1
A call() 0 10 1
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