<?php
namespace App\EventSubscriber;
use App\Entity\AuthorCmsInterface;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use ApiPlatform\Symfony\EventListener\EventPriorities;
class AddAuthorSubscriber implements EventSubscriberInterface
{
public function __construct(private readonly TokenStorageInterface $tokenStorage)
{
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['attachAuthor', EventPriorities::PRE_WRITE],
];
}
public function attachAuthor(ViewEvent $event)
{
$controllerResulte = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (
!$controllerResulte instanceof AuthorCmsInterface
|| Request::METHOD_POST !== $method) {
return;
}
$token = $this->tokenStorage->getToken();
if (!$token) {
return;
}
$owner = $token->getUser();
if (!$owner instanceof User) {
return;
}
$controllerResulte->setAuthor($owner);
}
}