1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\EventProjector\EventHandlers; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
6
|
|
|
use Spatie\EventProjector\StoredEvent; |
7
|
|
|
|
8
|
|
|
final class EventHandlerCollection |
9
|
|
|
{ |
10
|
|
|
/** @var \Illuminate\Support\Collection */ |
11
|
|
|
private $eventHandlers; |
12
|
|
|
|
13
|
|
|
public function __construct($eventHandlers = []) |
14
|
|
|
{ |
15
|
|
|
$this->eventHandlers = collect(); |
16
|
|
|
|
17
|
|
|
foreach ($eventHandlers as $eventHandler) { |
18
|
|
|
$this->add($eventHandler); |
19
|
|
|
} |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function add(EventHandler $eventHandler): void |
23
|
|
|
{ |
24
|
|
|
$this->eventHandlers[get_class($eventHandler)] = $eventHandler; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function all(): Collection |
28
|
|
|
{ |
29
|
|
|
return $this->eventHandlers; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function forEvent(StoredEvent $storedEvent): Collection |
33
|
|
|
{ |
34
|
|
|
return $this->eventHandlers->filter(function (EventHandler $eventHandler) use ($storedEvent) { |
35
|
|
|
return in_array($storedEvent->event_class, $eventHandler->handles(), true); |
36
|
|
|
}); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function call(string $method) |
40
|
|
|
{ |
41
|
|
|
$this->eventHandlers |
42
|
|
|
->filter(function (EventHandler $eventHandler) use ($method) { |
43
|
|
|
return method_exists($eventHandler, $method); |
44
|
|
|
}) |
45
|
|
|
->each(function (EventHandler $eventHandler) use ($method) { |
46
|
|
|
return app()->call([$eventHandler, $method]); |
47
|
|
|
}); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function remove(array $eventHandlerClassNames): void |
51
|
|
|
{ |
52
|
|
|
$this->eventHandlers = $this->eventHandlers |
53
|
|
|
->reject(function (EventHandler $eventHandler) use ($eventHandlerClassNames) { |
54
|
|
|
return in_array(get_class($eventHandler), $eventHandlerClassNames); |
55
|
|
|
}); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|