1 | <?php |
||
11 | class ReplayCommand extends Command |
||
12 | { |
||
13 | protected $signature = 'event-projector:replay {projector?*} |
||
14 | {--from=0 : Replay events starting from this event number} |
||
15 | {--stored-event-model= : Replay events from this store}'; |
||
16 | |||
17 | protected $description = 'Replay stored events'; |
||
18 | |||
19 | /** @var \Spatie\EventProjector\Projectionist */ |
||
20 | protected $projectionist; |
||
21 | |||
22 | public function __construct(Projectionist $projectionist) |
||
23 | { |
||
24 | parent::__construct(); |
||
25 | |||
26 | $this->projectionist = $projectionist; |
||
27 | } |
||
28 | |||
29 | public function handle(): void |
||
30 | { |
||
31 | $projectors = $this->selectProjectors($this->argument('projector')); |
||
32 | |||
33 | if (is_null($projectors)) { |
||
34 | $this->warn('No events replayed!'); |
||
35 | |||
36 | return; |
||
37 | } |
||
38 | |||
39 | $this->replay($projectors, $this->option('from')); |
||
40 | } |
||
41 | |||
42 | public function selectProjectors(array $projectorClassNames): ?Collection |
||
43 | { |
||
44 | if (count($projectorClassNames ?? []) === 0) { |
||
45 | if (! $confirmed = $this->confirm('Are you sure you want to replay events to all projectors?'), true) { |
||
|
|||
46 | return null; |
||
47 | } |
||
48 | |||
49 | return $this->projectionist->getProjectors(); |
||
50 | } |
||
51 | |||
52 | return collect($projectorClassNames) |
||
53 | ->map(function (string $projectorName) { |
||
54 | return ltrim($projectorName, '\\'); |
||
55 | }) |
||
56 | ->map(function (string $projectorName) { |
||
57 | if (! $projector = $this->projectionist->getProjector($projectorName)) { |
||
58 | throw new Exception("Projector {$projectorName} not found. Did you register it?"); |
||
59 | } |
||
60 | |||
61 | return $projector; |
||
62 | }); |
||
63 | } |
||
64 | |||
65 | public function replay(Collection $projectors, int $startingFrom): void |
||
66 | { |
||
67 | $repository = app(StoredEventRepository::class); |
||
68 | $events = $repository->retrieveAllStartingFrom($startingFrom); |
||
69 | $replayCount = $events->count(); |
||
70 | |||
71 | if ($replayCount === 0) { |
||
72 | $this->warn('There are no events to replay'); |
||
73 | |||
74 | return; |
||
75 | } |
||
76 | |||
77 | $this->comment("Replaying {$replayCount} events..."); |
||
78 | |||
79 | $bar = $this->output->createProgressBar($events->count()); |
||
80 | $onEventReplayed = function () use ($bar) { |
||
81 | $bar->advance(); |
||
82 | }; |
||
83 | |||
84 | $this->projectionist->replay($projectors, $startingFrom, $onEventReplayed); |
||
85 | |||
86 | $bar->finish(); |
||
87 | |||
88 | $this->emptyLine(2); |
||
89 | $this->comment('All done!'); |
||
90 | } |
||
91 | |||
92 | private function emptyLine(int $amount = 1): void |
||
93 | { |
||
94 | foreach (range(1, $amount) as $i) { |
||
95 | $this->line(''); |
||
96 | } |
||
97 | } |
||
98 | } |
||
99 |