<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use ApiPlatform\Core\Validator\ValidatorInterface;
use JetBrains\PhpStorm\ArrayShape;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class PreDeleteSubscriber implements EventSubscriberInterface
{
public const PRE_REMOVE_VALIDATION_GROUP = 'deletable';
private ValidatorInterface $validator;
public function __construct(ValidatorInterface $validator)
{
$this->validator = $validator;
}
#[ArrayShape([KernelEvents::VIEW => 'array'])]
public static function getSubscribedEvents(): array
{
return [
KernelEvents::VIEW => ['preDelete', EventPriorities::PRE_WRITE],
];
}
public function preDelete(ViewEvent $viewEvent): void
{
$entity = $viewEvent->getControllerResult();
$method = $viewEvent->getRequest()->getMethod();
if (Request::METHOD_DELETE === $method) {
$this->validator->validate(
$entity,
['groups' => self::PRE_REMOVE_VALIDATION_GROUP]
);
}
}
}