<?php
declare(strict_types=1);
namespace App\EventSubscriber\Request;
use ApiPlatform\Symfony\EventListener\EventPriorities;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Security;
use App\Entity\Request as RequestEntity;
final class ApiCreateSubscriber implements EventSubscriberInterface
{
public function __construct(
protected Security $security
) {}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => [
['setCurrentUserAsApplicant', EventPriorities::PRE_WRITE],
],
];
}
public function setCurrentUserAsApplicant(ViewEvent $event): void
{
$entity = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$entity instanceof RequestEntity || Request::METHOD_POST !== $method) {
return;
}
$entity->applicant = $this->security->getUser();
}
}