Search code examples
symfonydoctrineevent-listenersymfony-3.4

Symfony listener - postUpdate doublon


I'm running Symfony 3 LTS. I have a Suscriber listening to the postUpdate event in order to log into DB all the activity on products in my database. Below is my code:

use AppBundle\Entity\History;

public function getSubscribedEvents()
{
    return [
        Events::postUpdate,
    ];
}

public function postUpdate(LifecycleEventArgs $args)
{
    if(!is_null($this->tokenStorage->getToken())) {
        $user = $this->tokenStorage->getToken()->getUser();
        $entity = $args->getObject();
        $em = $args->getEntityManager();
        if ($entity instanceof Product) {
            $history = new History($user, "Product #5 has been updated");
            $em->persist($history);
        }
        $em->flush();
    }
}

Problem: History is inserted twice in the database. I can't figure out why. I tried to remove the persist() and/or flush() methods but nothing is created.

PS: there is no relationship between my entities Product and History. And it must not. My issue is only the duplicate behavior.

enter image description here


Solution

  • I don't have the correct answer but there is a workaround :

    use AppBundle\Entity\History;
    
        // Will contains the User ID to avoid duplicate log
        private $flushed = [];
    
        public function getSubscribedEvents()
        {
            return [
                Events::postUpdate,
            ];
        }
    
        public function postUpdate(LifecycleEventArgs $args)
        {
            if(!is_null($this->tokenStorage->getToken())) {
                $user = $this->tokenStorage->getToken()->getUser();
                $entity = $args->getObject();
                $em = $args->getEntityManager();
                                                // Check that the User.id is not already created in History during the update PHP Process
                if ($entity instanceof Product && !in_array($user->getId(), $this->flushed)) {
                    $history = new History($user, "Product #5 has been updated");
                    $em->persist($history);
                    // Add the user ID in our array to avoid duplicate
                    $this->flushed[] = $user->getId();
                }
                $em->flush();
            }
        }