|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Tempest\CommandBus; |
| 6 | + |
| 7 | +use Tempest\Console\Console; |
| 8 | +use Tempest\Console\ConsoleCommand; |
| 9 | +use Tempest\Console\ExitCode; |
| 10 | +use Tempest\Console\HasConsole; |
| 11 | +use Tempest\Container\Container; |
| 12 | +use function Tempest\Support\arr; |
| 13 | +use Throwable; |
| 14 | + |
| 15 | +final readonly class HandleAsyncCommand |
| 16 | +{ |
| 17 | + use HasConsole; |
| 18 | + |
| 19 | + public function __construct( |
| 20 | + private CommandBusConfig $commandBusConfig, |
| 21 | + private Container $container, |
| 22 | + private Console $console, |
| 23 | + private CommandRepository $repository, |
| 24 | + ) { |
| 25 | + } |
| 26 | + |
| 27 | + #[ConsoleCommand(name: 'command:handle')] |
| 28 | + public function __invoke(?string $uuid = null): ExitCode |
| 29 | + { |
| 30 | + try { |
| 31 | + if ($uuid) { |
| 32 | + $command = $this->repository->findPendingCommand($uuid); |
| 33 | + } else { |
| 34 | + $command = arr($this->repository->getPendingCommands())->first(); |
| 35 | + } |
| 36 | + |
| 37 | + if (! $command) { |
| 38 | + $this->error('No pending command found'); |
| 39 | + |
| 40 | + return ExitCode::ERROR; |
| 41 | + } |
| 42 | + |
| 43 | + $commandHandler = $this->commandBusConfig->handlers[$command::class] ?? null; |
| 44 | + |
| 45 | + if (! $commandHandler) { |
| 46 | + $commandClass = $command::class; |
| 47 | + $this->error("No handler found for command {$commandClass}"); |
| 48 | + |
| 49 | + return ExitCode::ERROR; |
| 50 | + } |
| 51 | + |
| 52 | + $commandHandler->handler->invokeArgs( |
| 53 | + $this->container->get($commandHandler->handler->getDeclaringClass()->getName()), |
| 54 | + [$command], |
| 55 | + ); |
| 56 | + |
| 57 | + $this->repository->markAsDone($uuid); |
| 58 | + $this->success('Done'); |
| 59 | + |
| 60 | + return ExitCode::SUCCESS; |
| 61 | + } catch (Throwable $throwable) { |
| 62 | + $this->repository->markAsFailed($uuid); |
| 63 | + $this->error($throwable->getMessage()); |
| 64 | + |
| 65 | + return ExitCode::ERROR; |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments