src/EventSubscriber/PreDeleteSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use ApiPlatform\Core\Validator\ValidatorInterface;
  5. use JetBrains\PhpStorm\ArrayShape;
  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. class PreDeleteSubscriber implements EventSubscriberInterface
  11. {
  12.     public const PRE_REMOVE_VALIDATION_GROUP 'deletable';
  13.     private ValidatorInterface $validator;
  14.     public function __construct(ValidatorInterface $validator)
  15.     {
  16.         $this->validator $validator;
  17.     }
  18.     #[ArrayShape([KernelEvents::VIEW => 'array'])]
  19.     public static function getSubscribedEvents(): array
  20.     {
  21.         return [
  22.             KernelEvents::VIEW => ['preDelete'EventPriorities::PRE_WRITE],
  23.         ];
  24.     }
  25.     public function preDelete(ViewEvent $viewEvent): void
  26.     {
  27.         $entity $viewEvent->getControllerResult();
  28.         $method $viewEvent->getRequest()->getMethod();
  29.         if (Request::METHOD_DELETE === $method) {
  30.             $this->validator->validate(
  31.                 $entity,
  32.                 ['groups' => self::PRE_REMOVE_VALIDATION_GROUP]
  33.             );
  34.         }
  35.     }
  36. }