Search code examples
phpsymfonydoctrine-ormdoctrineapi-platform.com

Symfony prevent operation on entity using listeners


I'm trying to implement a SoftDelete. Yes, I'm aware of Gedmo.

I'm trying to implement the following logic, to set the softdelete value instead of deleting the entity:

#[AsDoctrineListener(Events::preRemove)]
class SoftDeleteEventListener
{
    public function preRemove(PreRemoveEventArgs $args): void
    {
        $entityManager = $args->getObjectManager();
        $entity = $args->getObject();
        $reflection = new \ReflectionClass($entity);
        $traits = $reflection->getTraitNames();

        if (in_array(SoftDeleteTrait::class, $traits)) {
            $entity->setDeletedAt(new \DateTimeImmutable());
            // cancel the deletion and persist the entity
            return;
        }
        
        // Go with the usual flow, flush
    }
}

The above code results in the entity deletion.

I'm using API platform, so I'm looking for unified logic for all my entities, without having to implement it in custom controllers.

I'm using Symfony 7.

Thank you


Solution

  • I ended up using an API platform state processor:

    class SoftDeleteStateProcessor implements ProcessorInterface
    {
        public function __construct(private readonly EntityManagerInterface $entityManager)
        {}
    
        public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): void
        {
            $data->setDeletedAt(new \DateTimeImmutable());
            $this->entityManager->persist($data);
            $this->entityManager->flush();
        }
    }
    
    

    The drawback is that I have to specify this processor on every entity, but that is a tradeoff I am willing to make.