Completed
Push — master ( 54f797...c92ba1 )
by Freek
12:52
created

EventProjectionist::callEventHandlers()   C

Complexity

Conditions 8
Paths 1

Size

Total Lines 44
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 44
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 24
nc 1
nop 2
1
<?php
2
3
namespace Spatie\EventProjector;
4
5
use Exception;
6
use Illuminate\Support\Collection;
7
use Spatie\EventProjector\Models\StoredEvent;
8
use Spatie\EventProjector\Projectors\Projector;
9
use Spatie\EventProjector\EventHandlers\EventHandler;
10
use Spatie\EventProjector\Events\FinishedEventReplay;
11
use Spatie\EventProjector\Events\StartingEventReplay;
12
use Spatie\EventProjector\Exceptions\InvalidEventHandler;
13
use Spatie\EventProjector\Events\EventHandlerFailedHandlingEvent;
14
use Spatie\EventProjector\Events\ProjectorDidNotHandlePriorEvents;
15
16
class EventProjectionist
17
{
18
    /** @var \Illuminate\Support\Collection */
19
    protected $projectors;
20
21
    /** @var \Illuminate\Support\Collection */
22
    protected $reactors;
23
24
    /** @var bool */
25
    protected $isReplayingEvents = false;
26
27
    /** @var int */
28
    protected $config;
29
30
    public function __construct(array $config)
31
    {
32
        $this->projectors = collect();
33
34
        $this->reactors = collect();
35
36
        $this->config = $config;
0 ignored issues
show
Documentation Bug introduced by
It seems like $config of type array is incompatible with the declared type integer of property $config.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
37
    }
38
39
    public function isReplayingEvents(): bool
40
    {
41
        return $this->isReplayingEvents;
42
    }
43
44
    public function addProjector($projector): self
45
    {
46
        $this->guardAgainstInvalidEventHandler($projector);
47
48
        if ($this->alreadyAdded('projector', $projector)) {
49
            return $this;
50
        }
51
52
        $this->projectors->push($projector);
53
54
        return $this;
55
    }
56
57
    public function addProjectors(array $projectors): self
58
    {
59
        collect($projectors)->each(function ($projector) {
60
            $this->addProjector($projector);
61
        });
62
63
        return $this;
64
    }
65
66
    public function getProjectors(): Collection
67
    {
68
        return $this->projectors;
69
    }
70
71
    public function getProjector(string $name): ?Projector
72
    {
73
        return $this
74
            ->instantiate($this->projectors)
75
            ->first(function (Projector $projector) use ($name) {
76
                return $projector->getName() === $name;
77
            });
78
    }
79
80
    public function addReactor($reactor): self
81
    {
82
        $this->guardAgainstInvalidEventHandler($reactor);
83
84
        if ($this->alreadyAdded('reactor', $reactor)) {
85
            return $this;
86
        }
87
88
        $this->reactors->push($reactor);
89
90
        return $this;
91
    }
92
93
    public function addReactors(array $reactors): self
94
    {
95
        collect($reactors)->each(function ($reactor) {
96
            $this->addReactor($reactor);
97
        });
98
99
        return $this;
100
    }
101
102
    public function getReactors(): Collection
103
    {
104
        return $this->reactors;
105
    }
106
107
    public function storeEvent(ShouldBeStored $event)
108
    {
109
        $storedEvent = $this->config['stored_event_model']::createForEvent($event);
110
111
        $this->handleImmediately($storedEvent);
112
113
        dispatch(new HandleStoredEventJob($storedEvent))->onQueue($this->config['queue']);
114
    }
115
116
    public function handle(StoredEvent $storedEvent)
117
    {
118
        $this
119
            ->callEventHandlers($this->projectors, $storedEvent)
120
            ->callEventHandlers($this->reactors, $storedEvent);
121
    }
122
123
    public function handleImmediately(StoredEvent $storedEvent)
124
    {
125
        $projectors = $this->instantiate($this->projectors);
126
127
        $projectors = $projectors->filter->shouldBeCalledImmediately();
128
129
        $this->callEventHandlers($projectors, $storedEvent);
130
    }
131
132
    protected function callEventHandlers(Collection $eventHandlers, StoredEvent $storedEvent): self
133
    {
134
        $eventHandlers
135
            ->pipe(function (Collection $eventHandlers) {
136
                return $this->instantiate($eventHandlers);
137
            })
138
            ->filter(function (EventHandler $eventHandler) use ($storedEvent) {
139
                if (! $eventHandler instanceof Projector) {
140
                    return true;
141
                }
142
143
                $event = $storedEvent->event;
144
145
                if (! $method = $eventHandler->methodNameThatHandlesEvent($event)) {
146
                    return false;
147
                }
148
149
                if (! method_exists($eventHandler, $method)) {
150
                    throw InvalidEventHandler::eventHandlingMethodDoesNotExist($eventHandler, $event, $method);
0 ignored issues
show
Documentation introduced by
$eventHandler is of type object<Spatie\EventProje...r\Projectors\Projector>, but the function expects a object<Spatie\EventProjector\Exceptions\object>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
151
                }
152
153
                return true;
154
            })
155
            ->filter(function (EventHandler $eventHandler) use ($storedEvent) {
156
                if ($eventHandler instanceof Projector) {
157
                    if (! $eventHandler->hasReceivedAllPriorEvents($storedEvent)) {
158
                        event(new ProjectorDidNotHandlePriorEvents($eventHandler, $storedEvent));
159
160
                        return false;
161
                    }
162
                }
163
164
                return true;
165
            })
166
            ->each(function (EventHandler $eventHandler) use ($storedEvent) {
167
                $eventWasHandledSuccessfully = $this->callEventHandler($eventHandler, $storedEvent);
168
169
                if ($eventHandler instanceof Projector && $eventWasHandledSuccessfully) {
170
                    $eventHandler->rememberReceivedEvent($storedEvent);
171
                }
172
            });
173
174
        return $this;
175
    }
176
177
    protected function callEventHandler(EventHandler $eventHandler, StoredEvent $storedEvent): bool
178
    {
179
        $event = $storedEvent->event;
180
181
        if (! $method = $eventHandler->methodNameThatHandlesEvent($event)) {
182
            return true;
183
        }
184
185
        try {
186
            app()->call([$eventHandler, $method], compact('event', 'storedEvent'));
187
        } catch (Exception $exception) {
188
            if (! $this->config['catch_exceptions']) {
189
                throw $exception;
190
            }
191
192
            $eventHandler->handleException($exception);
193
194
            event(new EventHandlerFailedHandlingEvent($eventHandler, $storedEvent, $exception));
195
196
            return false;
197
        }
198
199
        return true;
200
    }
201
202
    public function replayEvents(Collection $projectors, int $afterStoredEventId = 0, callable $onEventReplayed = null)
203
    {
204
        $this->isReplayingEvents = true;
205
206
        event(new StartingEventReplay($projectors));
207
208
        $projectors = $this->instantiate($projectors);
209
210
        $this->callMethod($projectors, 'onStartingEventReplay');
211
212
        StoredEvent::query()
213
            ->after($afterStoredEventId ?? 0)
214
            ->chunk($this->config['replay_chunk_size'], function (Collection $storedEvents) use ($projectors, $onEventReplayed) {
215
                $storedEvents->each(function (StoredEvent $storedEvent) use ($projectors, $onEventReplayed) {
216
                    $this->callEventHandlers($projectors, $storedEvent);
217
218
                    if ($onEventReplayed) {
219
                        $onEventReplayed($storedEvent);
220
                    }
221
                });
222
            });
223
224
        $this->isReplayingEvents = false;
225
226
        event(new FinishedEventReplay());
227
228
        $this->callMethod($projectors, 'onFinishedEventReplay');
229
    }
230
231
    protected function guardAgainstInvalidEventHandler($eventHandler)
232
    {
233
        if (! is_string($eventHandler)) {
234
            return;
235
        }
236
237
        if (! class_exists($eventHandler)) {
238
            throw InvalidEventHandler::doesNotExist($eventHandler);
239
        }
240
    }
241
242
    protected function instantiate(Collection $eventHandlers)
243
    {
244
        return $eventHandlers->map(function ($eventHandler) {
245
            if (is_string($eventHandler)) {
246
                $eventHandler = app($eventHandler);
247
            }
248
249
            return $eventHandler;
250
        });
251
    }
252
253
    protected function callMethod(Collection $eventHandlers, string $method): self
254
    {
255
        $eventHandlers
256
            ->filter(function (EventHandler $eventHandler) use ($method) {
257
                return method_exists($eventHandler, $method);
258
            })
259
            ->each(function (EventHandler $eventHandler) use ($method) {
260
                return app()->call([$eventHandler, $method]);
261
            });
262
263
        return $this;
264
    }
265
266
    protected function alreadyAdded(string $type, $eventHandler)
267
    {
268
        $eventHandlerClassName = is_string($eventHandler)
269
            ? $eventHandler
270
            : get_class($eventHandler);
271
272
        $variableName = "{$type}s";
273
274
        $currentEventHandlers = $this->$variableName->toArray();
275
276
        if (in_array($eventHandlerClassName, $currentEventHandlers)) {
277
            return $this;
278
        }
279
    }
280
281
    protected function getClassNames(Collection $eventHandlers): array
282
    {
283
        return $eventHandlers
284
            ->map(function ($eventHandler) {
285
                if (is_string($eventHandler)) {
286
                    return $eventHandler;
287
                }
288
289
                return get_class($eventHandler);
290
            })
291
            ->toArray();
292
    }
293
}
294