|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Patchlevel\EventSourcing\Console\Command; |
| 6 | + |
| 7 | +use Patchlevel\EventSourcing\Console\InputHelper; |
| 8 | +use Patchlevel\EventSourcing\Console\OutputStyle; |
| 9 | +use Patchlevel\EventSourcing\Message\Pipe; |
| 10 | +use Patchlevel\EventSourcing\Message\Translator\Translator; |
| 11 | +use Patchlevel\EventSourcing\Store\Store; |
| 12 | +use Symfony\Component\Console\Attribute\AsCommand; |
| 13 | +use Symfony\Component\Console\Command\Command; |
| 14 | +use Symfony\Component\Console\Input\InputInterface; |
| 15 | +use Symfony\Component\Console\Input\InputOption; |
| 16 | +use Symfony\Component\Console\Output\OutputInterface; |
| 17 | + |
| 18 | +use function count; |
| 19 | + |
| 20 | +#[AsCommand( |
| 21 | + 'event-sourcing:store:migrate', |
| 22 | + 'migrate events from one store to another', |
| 23 | +)] |
| 24 | +final class StoreMigrateCommand extends Command |
| 25 | +{ |
| 26 | + /** @param iterable<int, Translator> $translators */ |
| 27 | + public function __construct( |
| 28 | + private readonly Store $store, |
| 29 | + private readonly Store $newStore, |
| 30 | + private readonly iterable $translators = [], |
| 31 | + ) { |
| 32 | + parent::__construct(); |
| 33 | + } |
| 34 | + |
| 35 | + protected function configure(): void |
| 36 | + { |
| 37 | + $this |
| 38 | + ->addOption( |
| 39 | + 'buffer', |
| 40 | + null, |
| 41 | + InputOption::VALUE_REQUIRED, |
| 42 | + 'How many messages should be buffered', |
| 43 | + 1_000, |
| 44 | + ); |
| 45 | + } |
| 46 | + |
| 47 | + protected function execute(InputInterface $input, OutputInterface $output): int |
| 48 | + { |
| 49 | + $buffer = InputHelper::positiveIntOrZero($input->getOption('buffer')); |
| 50 | + $style = new OutputStyle($input, $output); |
| 51 | + |
| 52 | + $style->info('Migration initialization...'); |
| 53 | + |
| 54 | + $count = $this->store->count(); |
| 55 | + $messages = $this->store->load(); |
| 56 | + |
| 57 | + $style->progressStart($count); |
| 58 | + |
| 59 | + $bufferedMessages = []; |
| 60 | + |
| 61 | + $pipe = new Pipe( |
| 62 | + $messages, |
| 63 | + ...$this->translators, |
| 64 | + ); |
| 65 | + |
| 66 | + foreach ($pipe as $message) { |
| 67 | + $bufferedMessages[] = $message; |
| 68 | + |
| 69 | + if (count($bufferedMessages) < $buffer) { |
| 70 | + continue; |
| 71 | + } |
| 72 | + |
| 73 | + $this->newStore->save(...$bufferedMessages); |
| 74 | + $bufferedMessages = []; |
| 75 | + $style->progressAdvance($buffer); |
| 76 | + } |
| 77 | + |
| 78 | + if (count($bufferedMessages) !== 0) { |
| 79 | + $this->newStore->save(...$bufferedMessages); |
| 80 | + $style->progressAdvance(count($bufferedMessages)); |
| 81 | + } |
| 82 | + |
| 83 | + $style->progressFinish(); |
| 84 | + $style->success('Migration finished'); |
| 85 | + |
| 86 | + return 0; |
| 87 | + } |
| 88 | +} |
0 commit comments