src/EventSubscriber/JobStatusChangeSubscriber.php line 35

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use ApiPlatform\Symfony\EventListener\EventPriorities;
  5. use App\Entity\Job;
  6. use App\Entity\JobStatusLog;
  7. use App\Entity\Schedule;
  8. use App\Entity\User;
  9. use Doctrine\Persistence\ManagerRegistry;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\HttpKernel\Event\ViewEvent;
  12. use Symfony\Component\HttpKernel\KernelEvents;
  13. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  14. final class JobStatusChangeSubscriber implements EventSubscriberInterface
  15. {
  16.     public function __construct(
  17.         private readonly ManagerRegistry $managerRegistry,
  18.         private readonly TokenStorageInterface $tokenStorage,
  19.     )
  20.     {
  21.     }
  22.     public static function getSubscribedEvents(): array
  23.     {
  24.         return [
  25.             KernelEvents::VIEW => ['addStatusLog'EventPriorities::POST_WRITE],
  26.         ];
  27.     }
  28.     public function addStatusLog(ViewEvent $event): void
  29.     {
  30.         if ($event->getRequest()->getMethod() !== 'PUT') {
  31.             return;
  32.         }
  33.         $job $event->getControllerResult();
  34.         if ($job instanceof Schedule) {
  35.             $job $job->getJob();
  36.         }
  37.         if (!$job instanceof Job) {
  38.             return;
  39.         }
  40.         $log = new JobStatusLog();
  41.         $log->setJob($job);
  42.         $log->setStatus($job->getStatus());
  43.         $currentUser $this->tokenStorage->getToken()?->getUser();
  44.         if ($currentUser instanceof User) {
  45.             $log->setUser($currentUser);
  46.         }
  47.         $em $this->managerRegistry->getManager();
  48.         $em->persist($log);
  49.         $em->flush();
  50.     }
  51. }