src/EventSubscriber/LabelCreateEventSubscriber.php line 30

  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use ApiPlatform\Core\EventListener\EventPriorities;
  5. use App\Entity\Label;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpKernel\Event\ViewEvent;
  9. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  12. final class LabelCreateEventSubscriber implements EventSubscriberInterface
  13. {
  14.     public function __construct(private readonly TokenStorageInterface $tokenStorage)
  15.     {
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             KernelEvents::VIEW => ['createItemSequence'EventPriorities::PRE_WRITE]
  21.         ];
  22.     }
  23.     public function createItemSequence(ViewEvent $event): void
  24.     {
  25.         $entity $event->getControllerResult();
  26.         if (
  27.             !$entity instanceof Label
  28.             ||
  29.             $event->getRequest()->getMethod() !== Request::METHOD_POST
  30.         ) {
  31.             return;
  32.         }
  33.         $user $this->tokenStorage
  34.             ->getToken()
  35.             ->getUser();
  36.         if (null === $user) {
  37.             throw new NotFoundHttpException();
  38.         }
  39.         $entity->setInstitution($user->getCurrentInstitution());
  40.     }
  41. }