src/EventSubscriber/EntitySubscriber.php line 53

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\Reservation;
  5. use App\Entity\User;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpKernel\Event\ViewEvent;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. use Symfony\Component\Security\Core\Security;
  12. final class EntitySubscriber implements EventSubscriberInterface
  13. {
  14.     public function __construct(
  15.         protected Security $security
  16.     ) {}
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             KernelEvents::VIEW => [
  21.                 ['checkLimit'EventPriorities::PRE_WRITE],
  22.                 ['addCreatedBy'EventPriorities::PRE_WRITE],
  23.             ],
  24.         ];
  25.     }
  26.     public function addCreatedBy(ViewEvent $httpEvent): void
  27.     {
  28.         $entity $httpEvent->getControllerResult();
  29.         $method $httpEvent->getRequest()->getMethod();
  30.         if (Request::METHOD_POST !== $method) {
  31.             return;
  32.         }
  33.         $user $this->security->getUser();
  34.         if (!$user || !property_exists($entity'createdBy')) {
  35.             return;
  36.         }
  37.         $rp = new \ReflectionProperty($entity'createdBy');
  38.         $type $rp->getType()->getName();
  39.         if ($type === User::class) {
  40.             $entity->createdBy $user;
  41.         }
  42.     }
  43.     public function checkLimit(ViewEvent $httpEvent): void
  44.     {
  45.         $reservation $httpEvent->getControllerResult();
  46.         $method $httpEvent->getRequest()->getMethod();
  47.         if (!$reservation instanceof Reservation || Request::METHOD_POST !== $method) {
  48.             return;
  49.         }
  50.         $event $reservation->event;
  51.         $seatLimit $event->seatLimit;
  52.         if (!$seatLimit) {
  53.             return;
  54.         }
  55.         $count $event->reservations->count();
  56.         if ($count >= $seatLimit) {
  57.             $httpEvent->setResponse(new JsonResponse(['message' => "Event's seat limit exceeded"], 400));
  58.         }
  59.     }
  60. }