<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use ApiPlatform\Symfony\EventListener\EventPriorities;
use App\Entity\Job;
use App\Entity\JobStatusLog;
use App\Entity\Schedule;
use App\Entity\User;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
final class JobStatusChangeSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly ManagerRegistry $managerRegistry,
private readonly TokenStorageInterface $tokenStorage,
)
{
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['addStatusLog', EventPriorities::POST_WRITE],
];
}
public function addStatusLog(ViewEvent $event): void
{
if ($event->getRequest()->getMethod() !== 'PUT') {
return;
}
$job = $event->getControllerResult();
if ($job instanceof Schedule) {
$job = $job->getJob();
}
if (!$job instanceof Job) {
return;
}
$log = new JobStatusLog();
$log->setJob($job);
$log->setStatus($job->getStatus());
$currentUser = $this->tokenStorage->getToken()?->getUser();
if ($currentUser instanceof User) {
$log->setUser($currentUser);
}
$em = $this->managerRegistry->getManager();
$em->persist($log);
$em->flush();
}
}