1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\EventProjector; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
6
|
|
|
use Spatie\EventProjector\Exceptions\InvalidEventHandler; |
7
|
|
|
|
8
|
|
|
class EventProjectionist |
9
|
|
|
{ |
10
|
|
|
/** @var \Illuminate\Support\Collection */ |
11
|
|
|
public $mutators; |
12
|
|
|
|
13
|
|
|
/** @var \Illuminate\Support\Collection */ |
14
|
|
|
public $reactors; |
15
|
|
|
|
16
|
|
|
public function __construct() |
17
|
|
|
{ |
18
|
|
|
$this->mutators = collect(); |
19
|
|
|
|
20
|
|
|
$this->reactors = collect(); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function addMutator(string $mutator): self |
24
|
|
|
{ |
25
|
|
|
if (! class_exists($mutator)) { |
26
|
|
|
throw InvalidEventHandler::doesNotExist($mutator); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
$this->mutators->push($mutator); |
30
|
|
|
|
31
|
|
|
return $this; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function registerMutators(array $mutators): self |
35
|
|
|
{ |
36
|
|
|
collect($mutators)->each(function ($mutator) { |
37
|
|
|
$this->addMutator($mutator); |
38
|
|
|
}); |
39
|
|
|
|
40
|
|
|
return $this; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function addReactor(string $reactor): self |
44
|
|
|
{ |
45
|
|
|
if (! class_exists($reactor)) { |
46
|
|
|
throw InvalidEventHandler::doesNotExist($reactor); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$this->reactors->push($reactor); |
50
|
|
|
|
51
|
|
|
return $this; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function registerReactors(array $reactors): self |
55
|
|
|
{ |
56
|
|
|
collect($reactors)->each(function ($reactor) { |
57
|
|
|
$this->addReactor($reactor); |
58
|
|
|
}); |
59
|
|
|
|
60
|
|
|
return $this; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function callEventHandlers(Collection $eventHandlers, ShouldBeStored $event): self |
64
|
|
|
{ |
65
|
|
|
$eventHandlers |
66
|
|
|
->map(function (string $eventHandlerClass) { |
67
|
|
|
return app($eventHandlerClass); |
68
|
|
|
}) |
69
|
|
|
->each(function (object $eventHandler) use ($event) { |
70
|
|
|
$this->callEventHandler($eventHandler, $event); |
71
|
|
|
}); |
72
|
|
|
|
73
|
|
|
return $this; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
protected function callEventHandler(object $eventHandler, ShouldBeStored $event) |
77
|
|
|
{ |
78
|
|
|
if (! isset($eventHandler->handlesEvents)) { |
79
|
|
|
throw InvalidEventHandler::cannotHandleEvents($eventHandler); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
if (! $method = $eventHandler->handlesEvents[get_class($event)] ?? false) { |
83
|
|
|
return; |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
if (! method_exists($eventHandler, $method)) { |
87
|
|
|
throw InvalidEventHandler::eventHandlingMethodDoesNotExist($eventHandler, $event, $method); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
app()->call([$eventHandler, $method], compact('event')); |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|