1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\EventProjector\Console; |
4
|
|
|
|
5
|
|
|
use Illuminate\Console\Command; |
6
|
|
|
use Illuminate\Support\Collection; |
7
|
|
|
use Spatie\EventProjector\StoredEvent; |
8
|
|
|
use Spatie\EventProjector\EventProjectionist; |
9
|
|
|
use Spatie\EventProjector\Exceptions\InvalidEventHandler; |
10
|
|
|
|
11
|
|
|
class ReplayEventsCommand extends Command |
12
|
|
|
{ |
13
|
|
|
protected $signature = 'event-projector:replay-events |
14
|
|
|
{--projector=*} : The projector that should receive the event'; |
15
|
|
|
|
16
|
|
|
protected $description = 'Replay stored events'; |
17
|
|
|
|
18
|
|
|
/** @var \Spatie\EventProjector\EventProjectionist */ |
19
|
|
|
protected $eventSorcerer; |
20
|
|
|
|
21
|
|
|
public function __construct(EventProjectionist $eventSorcerer) |
22
|
|
|
{ |
23
|
|
|
parent::__construct(); |
24
|
|
|
|
25
|
|
|
$this->eventSorcerer = $eventSorcerer; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function handle() |
29
|
|
|
{ |
30
|
|
|
$projectors = $this->getProjectors(); |
31
|
|
|
|
32
|
|
|
if ($projectors->isEmpty()) { |
33
|
|
|
$this->warn('No projectors found to replay events to...'); |
34
|
|
|
|
35
|
|
|
return; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
$this->comment('Replaying events...'); |
39
|
|
|
|
40
|
|
|
$bar = $this->output->createProgressBar(StoredEvent::count()); |
41
|
|
|
|
42
|
|
|
StoredEvent::chunk(1000, function (StoredEvent $storedEvent) use ($projectors, $bar) { |
43
|
|
|
$this->eventSorcerer->callEventHandlers($projectors, $storedEvent); |
44
|
|
|
|
45
|
|
|
$bar->advance(); |
46
|
|
|
}); |
47
|
|
|
|
48
|
|
|
$bar->finish(); |
49
|
|
|
|
50
|
|
|
$this->comment('All done!'); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
protected function getProjectors(): Collection |
54
|
|
|
{ |
55
|
|
|
$onlyCallProjectors = $this->option('projector'); |
56
|
|
|
|
57
|
|
|
$this->guardAgainstNonExistingProjectors($onlyCallProjectors); |
|
|
|
|
58
|
|
|
|
59
|
|
|
return $this->eventSorcerer->projectors |
60
|
|
|
->filter(function (string $projector) use ($onlyCallProjectors) { |
61
|
|
|
if (! count($onlyCallProjectors)) { |
62
|
|
|
return true; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return in_array($projector, $onlyCallProjectors); |
66
|
|
|
}); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
protected function guardAgainstNonExistingProjectors(array $onlyCallProjectors) |
70
|
|
|
{ |
71
|
|
|
foreach ($onlyCallProjectors as $projector) { |
72
|
|
|
if (! class_exists($projector)) { |
73
|
|
|
throw InvalidEventHandler::doesNotExist($projector); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.