src/EventSubscriber/MuestraInSesionSubscriber.php line 24

  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Symfony\EventListener\EventPriorities;
  4. use App\Entity\Muestra;
  5. use App\Exception\ObjectInUseException;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpKernel\Event\ViewEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. final class MuestraInSesionSubscriber implements EventSubscriberInterface
  11. {
  12.     public function __construct()
  13.     {
  14.     }
  15.     public static function getSubscribedEvents()
  16.     {
  17.         return [
  18.             KernelEvents::VIEW => ['checkSesion'EventPriorities::PRE_WRITE],
  19.         ];
  20.     }
  21.     public function checkSesion(ViewEvent $event): void
  22.     {
  23.         $muestra $event->getControllerResult();
  24.         $method $event->getRequest()->getMethod();
  25.         if (!$muestra instanceof Muestra || Request::METHOD_DELETE !== $method) {
  26.             return;
  27.         }
  28.         if ($muestra->getSesion() !== null && $muestra->isOriginal()) {
  29.             throw new ObjectInUseException(sprintf('La muestra "%s" no se puede eliminar porque pertenence a la sesion "%s"'$muestra->getNombre(), $muestra->getSesion()->getNombre()));
  30.         }
  31.     }
  32. }