Api-Platform: use validation_groups on DELETE action

Viewed 589

I am trying to prevent removal of an entity when it has some specific content. So I added a validation rules, and it is working perfectly with a regular controler using a form validation.

//entity
    /**
     * @Assert\IsTrue(message="Delete not allowed", groups="delete")
     *
     * @return bool
     */
    public function isDeleteAllowed(): bool
    {
        //some logic here...
        return false;
    }

Now I want to reuse the same logic for the api-platform part. I have setup a validation group for the delete action of my entity

//entity
/**
 * @ApiResource(
 *     itemOperations={
 *         "delete"={
 *              "validation_groups"={"delete"}
 *          }
 *     })
 */

However the api-platform DELETE action is skipping validation. How can I enforce it?

For your information, I found the reason why it is not working in the api-platform source code where they deliberately ignore validation on DELETE action. So I opened a ticket to see if it can be fixed Validation on DELETE action

1 Answers

Here is the solution we used to solve this hard-coded behavior in ApiPlatform by reversing it in an event subscriber:

<?php
//src\EventSubscriber\DeleteValidationSubscriber.php

namespace App\EventSubscriber;

use ApiPlatform\Core\Exception\ResourceClassNotFoundException;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use ApiPlatform\Core\Validator\ValidatorInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class DeleteValidationSubscriber implements EventSubscriberInterface
{
    private $validator;
    private $resourceMetadataFactory;

    /**
     * @param ValidatorInterface $validator
     * @param ResourceMetadataFactoryInterface $resourceMetadataFactory
     */
    public function __construct(ValidatorInterface $validator, ResourceMetadataFactoryInterface $resourceMetadataFactory)
    {
        $this->validator = $validator;
        $this->resourceMetadataFactory = $resourceMetadataFactory;
    }

    /**
     * Validates data returned by the controller for DELETE action because api-platform is ignoring it
     *
     * @param ViewEvent $event
     * @throws ResourceClassNotFoundException
     */
    public function onKernelView(ViewEvent $event)
    {
        $controllerResult = $event->getControllerResult();
        $request = $event->getRequest();

        if (
            $controllerResult instanceof Response
            || !$request->isMethod('DELETE')
            || $request->isMethodSafe()
            || !($attributes = RequestAttributesExtractor::extractAttributes($request))
            || !$attributes['receive']
        ) {
            return;
        }

        $resourceMetadata = $this->resourceMetadataFactory->create($attributes['resource_class']);

        $validationGroups = $resourceMetadata->getOperationAttribute($attributes, 'validation_groups', null, true);
        if (!is_null($validationGroups)) {
            $this->validator->validate($controllerResult, ['groups' => $validationGroups]);
        }
    }

    /**
     * @return array|string[]
     */
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => ['onKernelView', 64],
        ];
    }
}

With that in place, validation is working as expected whenever "validation_groups" is explicitly defined on the "delete" item operation without other extra code.

Related