Completed
Push — master ( 9e0b65...876221 )
by Freek
08:47 queued 05:37
created

EventProjectionist::callEventHandlers()   C

Complexity

Conditions 8
Paths 1

Size

Total Lines 45
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 45
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\ProjectorStatus;
8
use Spatie\EventProjector\Models\StoredEvent;
9
use Spatie\EventProjector\Projectors\Projector;
10
use Spatie\EventProjector\EventHandlers\EventHandler;
11
use Spatie\EventProjector\Events\FinishedEventReplay;
12
use Spatie\EventProjector\Events\StartingEventReplay;
13
use Spatie\EventProjector\Exceptions\InvalidEventHandler;
14
use Spatie\EventProjector\Events\EventHandlerFailedHandlingEvent;
15
use Spatie\EventProjector\Events\ProjectorDidNotHandlePriorEvents;
16
17
class EventProjectionist
18
{
19
    /** @var \Illuminate\Support\Collection */
20
    protected $projectors;
21
22
    /** @var \Illuminate\Support\Collection */
23
    protected $reactors;
24
25
    /** @var bool */
26
    protected $isReplayingEvents = false;
27
28
    /** @var int */
29
    protected $config;
30
31
    public function __construct(array $config)
32
    {
33
        $this->projectors = collect();
34
35
        $this->reactors = collect();
36
37
        $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...
38
    }
39
40
    public function isReplayingEvents(): bool
41
    {
42
        return $this->isReplayingEvents;
43
    }
44
45
    public function addProjector($projector): self
46
    {
47
        $this->guardAgainstInvalidEventHandler($projector);
48
49
        if ($this->alreadyAdded('projector', $projector)) {
50
            return $this;
51
        }
52
53
        $this->projectors->push($projector);
54
55
        return $this;
56
    }
57
58
    public function addProjectors(array $projectors): self
59
    {
60
        collect($projectors)->each(function ($projector) {
61
            $this->addProjector($projector);
62
        });
63
64
        return $this;
65
    }
66
67
    public function getProjectors(): Collection
68
    {
69
        return $this->projectors;
70
    }
71
72
    public function getProjector(string $name): ?Projector
73
    {
74
        return $this
75
            ->instantiate($this->projectors)
76
            ->first(function (Projector $projector) use ($name) {
77
                return $projector->getName() === $name;
78
            });
79
    }
80
81
    public function addReactor($reactor): self
82
    {
83
        $this->guardAgainstInvalidEventHandler($reactor);
84
85
        if ($this->alreadyAdded('reactor', $reactor)) {
86
            return $this;
87
        }
88
89
        $this->reactors->push($reactor);
90
91
        return $this;
92
    }
93
94
    public function addReactors(array $reactors): self
95
    {
96
        collect($reactors)->each(function ($reactor) {
97
            $this->addReactor($reactor);
98
        });
99
100
        return $this;
101
    }
102
103
    public function getReactors(): Collection
104
    {
105
        return $this->reactors;
106
    }
107
108
    public function handle(StoredEvent $storedEvent)
109
    {
110
        $this
111
            ->callEventHandlers($this->projectors, $storedEvent)
112
            ->callEventHandlers($this->reactors, $storedEvent);
113
    }
114
115
    public function handleImmediately(StoredEvent $storedEvent)
116
    {
117
        $projectors = $this->instantiate($this->projectors);
118
119
        $projectors = $projectors->filter->shouldBeCalledImmediately();
120
121
        $this->callEventHandlers($projectors, $storedEvent);
122
    }
123
124
    protected function callEventHandlers(Collection $eventHandlers, StoredEvent $storedEvent): self
125
    {
126
        $eventHandlers
127
            ->pipe(function (Collection $eventHandlers) {
128
                return $this->instantiate($eventHandlers);
129
            })
130
            ->filter(function(EventHandler $eventHandler) use ($storedEvent) {
131
                if (! $eventHandler instanceof Projector) {
132
                    return true;
133
                }
134
135
                $event = $storedEvent->event;
136
137
                if (! $method = $eventHandler->methodNameThatHandlesEvent($event)) {
138
                    return false;
139
                }
140
141
                if (! method_exists($eventHandler, $method)) {
142
                    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...
143
                }
144
                
145
                return true;
146
            })
147
            ->filter(function (EventHandler $eventHandler) use ($storedEvent) {
148
149
                if ($eventHandler instanceof Projector) {
150
                    if (! $eventHandler->hasReceivedAllPriorEvents($storedEvent)) {
151
                        event(new ProjectorDidNotHandlePriorEvents($eventHandler, $storedEvent));
152
153
                        return false;
154
                    }
155
                }
156
157
                return true;
158
            })
159
            ->each(function (EventHandler $eventHandler) use ($storedEvent) {
160
                $eventWasHandledSuccessfully = $this->callEventHandler($eventHandler, $storedEvent);
161
162
                if ($eventHandler instanceof Projector && $eventWasHandledSuccessfully) {
163
                    $eventHandler->rememberReceivedEvent($storedEvent);
164
                }
165
            });
166
167
        return $this;
168
    }
169
170
    protected function callEventHandler(EventHandler $eventHandler, StoredEvent $storedEvent): bool
171
    {
172
        $event = $storedEvent->event;
173
174
        if (! $method = $eventHandler->methodNameThatHandlesEvent($event)) {
175
            return true;
176
        }
177
178
        try {
179
            app()->call([$eventHandler, $method], compact('event', 'storedEvent'));
180
        } catch (Exception $exception) {
181
            if (! $this->config['catch_exceptions']) {
182
                throw $exception;
183
            }
184
185
            $eventHandler->handleException($exception);
186
187
            event(new EventHandlerFailedHandlingEvent($eventHandler, $storedEvent, $exception));
188
189
            return false;
190
        }
191
192
        return true;
193
    }
194
195
    public function replayEvents(Collection $projectors, int $afterStoredEventId = 0, callable $onEventReplayed = null)
196
    {
197
        $this->isReplayingEvents = true;
198
199
        event(new StartingEventReplay($projectors));
200
201
        $projectors = $this->instantiate($projectors);
202
203
        $this->callMethod($projectors, 'onStartingEventReplay');
204
205
        StoredEvent::query()
206
            ->after($afterStoredEventId ?? 0)
207
            ->chunk($this->config['replay_chunk_size'], function (Collection $storedEvents) use ($projectors, $onEventReplayed) {
208
                $storedEvents->each(function (StoredEvent $storedEvent) use ($projectors, $onEventReplayed) {
209
                    $this->callEventHandlers($projectors, $storedEvent);
210
211
                    if ($onEventReplayed) {
212
                        $onEventReplayed($storedEvent);
213
                    }
214
                });
215
            });
216
217
        $this->isReplayingEvents = false;
218
219
        event(new FinishedEventReplay());
220
221
        $this->callMethod($projectors, 'onFinishedEventReplay');
222
    }
223
224
    protected function guardAgainstInvalidEventHandler($eventHandler)
225
    {
226
        if (! is_string($eventHandler)) {
227
            return;
228
        }
229
230
        if (! class_exists($eventHandler)) {
231
            throw InvalidEventHandler::doesNotExist($eventHandler);
232
        }
233
    }
234
235
    protected function instantiate(Collection $eventHandlers)
236
    {
237
        return $eventHandlers->map(function ($eventHandler) {
238
            if (is_string($eventHandler)) {
239
                $eventHandler = app($eventHandler);
240
            }
241
242
            return $eventHandler;
243
        });
244
    }
245
246
    protected function callMethod(Collection $eventHandlers, string $method): self
247
    {
248
        $eventHandlers
249
            ->filter(function (EventHandler $eventHandler) use ($method) {
250
                return method_exists($eventHandler, $method);
251
            })
252
            ->each(function (EventHandler $eventHandler) use ($method) {
253
                return app()->call([$eventHandler, $method]);
254
            });
255
256
        return $this;
257
    }
258
259
    protected function alreadyAdded(string $type, $eventHandler)
260
    {
261
        $eventHandlerClassName = is_string($eventHandler)
262
            ? $eventHandler
263
            : get_class($eventHandler);
264
265
        $variableName = "{$type}s";
266
267
        $currentEventHandlers = $this->$variableName->toArray();
268
269
        if (in_array($eventHandlerClassName, $currentEventHandlers)) {
270
            return $this;
271
        }
272
    }
273
274
    protected function getClassNames(Collection $eventHandlers): array
275
    {
276
        return $eventHandlers
277
            ->map(function ($eventHandler) {
278
                if (is_string($eventHandler)) {
279
                    return $eventHandler;
280
                }
281
282
                return get_class($eventHandler);
283
            })
284
            ->toArray();
285
    }
286
}
287