0
votes

I have a question on api platform custom routes functionality. When trying to implement custom route with DELETE method the event system is triggered for object in http request (that is found by param converter):

* @ApiResource(
*     attributes={
*         "normalization_context": {
*         },
*         "denormalization_context": {
*         },
*     },
*     itemOperations={
*     },
*     collectionOperations={
*         "customObjectRemove": {
*             "method": "DELETE",
*             "path": "/objects/{id}/custom_remove",
*             "controller": CustomObjectRemoveController::class,

So, even I have written my own logic in controller my entity is always triggered for removal in api platform event system. How can I prevent this behavior?

1
Can you please provide more code for how you implemented your routers? - Johan
@Johan Updated. I've used ApiResource annotations in my model. My controller is api platform style - it has __invoke method. In controller if I return my object entity - api platform will trigger remove event, if it returns nothing - it's okay - alvery

1 Answers

2
votes

you can implement an event subscriber that implements EventSubscriberInterface:

<?php 
namespace App\EventSubscriber;

use ApiPlatform\Core\EventListener\EventPriorities;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\KernelEvents;


final class DeleteEntityNameSubscriber implements EventSubscriberInterface
{


    public function __construct()
    {
        // Inject the services you need
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => ['onDeleteAction', EventPriorities::PRE_WRITE]
        ];
    }

    public function onDeleteAction(GetResponseForControllerResultEvent $event)
    {
        $object = $event->getControllerResult();
        $request = $event->getRequest();
        $method = $request->getMethod();

        if (!$object instanceof MyEntity || Request::METHOD_DELETE !== $method) {
            return;
        }

       // Do you staff here
    }

}