|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Synolia\SyliusSchedulerCommandPlugin\EventSubscriber; |
| 6 | + |
| 7 | +use Doctrine\DBAL\Exception; |
| 8 | +use Symfony\Component\Console\ConsoleEvents; |
| 9 | +use Symfony\Component\Console\Event\ConsoleSignalEvent; |
| 10 | +use Symfony\Component\Console\Event\ConsoleTerminateEvent; |
| 11 | +use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 12 | +use Synolia\SyliusSchedulerCommandPlugin\Entity\ScheduledCommand; |
| 13 | +use Synolia\SyliusSchedulerCommandPlugin\Enum\ScheduledCommandStateEnum; |
| 14 | +use Synolia\SyliusSchedulerCommandPlugin\Repository\ScheduledCommandRepository; |
| 15 | + |
| 16 | +final class ConsoleSubscriber implements EventSubscriberInterface |
| 17 | +{ |
| 18 | + public function __construct( |
| 19 | + private readonly ScheduledCommandRepository $scheduledCommandRepository, |
| 20 | + ) { |
| 21 | + } |
| 22 | + |
| 23 | + public static function getSubscribedEvents(): array |
| 24 | + { |
| 25 | + return [ |
| 26 | + ConsoleEvents::TERMINATE => 'onConsoleTerminate', |
| 27 | + ConsoleEvents::SIGNAL => 'onConsoleSignal', |
| 28 | + ]; |
| 29 | + } |
| 30 | + |
| 31 | + public function onConsoleTerminate(ConsoleTerminateEvent $event): void |
| 32 | + { |
| 33 | + $this->updateCommand($event); |
| 34 | + } |
| 35 | + |
| 36 | + public function onConsoleSignal(ConsoleSignalEvent $event): void |
| 37 | + { |
| 38 | + $this->updateCommand($event); |
| 39 | + } |
| 40 | + |
| 41 | + private function updateCommand(ConsoleSignalEvent|ConsoleTerminateEvent $event): void |
| 42 | + { |
| 43 | + try { |
| 44 | + $commandCode = $event->getCommand()?->getName() ?? 'no_command'; |
| 45 | + /** @var ScheduledCommand|null $schedulerCommand */ |
| 46 | + $schedulerCommand = $this->scheduledCommandRepository->findOneBy(['command' => $commandCode], ['id' => 'DESC']); |
| 47 | + } catch (Exception) { |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + if (null === $schedulerCommand) { |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + if ($schedulerCommand->getState() !== ScheduledCommandStateEnum::IN_PROGRESS) { |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + $exitCode = $event->getExitCode(); |
| 60 | + if (false === $exitCode) { |
| 61 | + $exitCode = -1; |
| 62 | + } |
| 63 | + |
| 64 | + $schedulerCommand->setCommandEndTime(new \DateTime()); |
| 65 | + $schedulerCommand->setState(ScheduledCommandStateEnum::TERMINATION); |
| 66 | + $schedulerCommand->setLastReturnCode($exitCode); |
| 67 | + $this->scheduledCommandRepository->add($schedulerCommand); |
| 68 | + } |
| 69 | +} |
0 commit comments