Search code examples
symfonydoctrineentitymanager

Symfony & doctrine : object not updated in a search


I am testing a certain action in phpUnit.

In my test, I get the entity manager from container. I create an entity $finalisation, and then insert it in my table :

public function testAction()
{

self::bootKernel();
        $em = static::$kernel->getContainer()
        ->get('doctrine')
        ->getManager()
        ;
//I create some $finalisation entity, and insert it
(...)
$em->persist($finalisation);
$em->flush();

//I call then the action to test (my function authentification works well)
$crawler = $this->authentification("/annonce/finaliser-annonce/annonce-en-cours-4");
// (... MORE CODE SEE BELOW)
}

This action is meant to change the $finalisation object via a service (GestionnaireFinalisation) : the field finaliseParAuteur of $finalisation is turned from false to true.

Now, I have the service, called GestionnaireFinalisation, who transforms the field in the object $finalisation from FALSE to TRUE

class GestionnaireFinalisation 
{
    protected $em;

    public function __construct(EntityManager $entityManager){
        $this->em = $entityManager;
    }

public function finalisationParAuteur($annonceEnCours, $profilAuteur)
    {
        $finalisation = $this->em->getRepository('AppBundle:Finalisation')
        ->findFinalisationParProfilAuteur($annonceEnCours, $profilAuteur);

        if ($finalisation->getFinaliseParPresta())
        {
            // ... THIS CODE IS NOT RUN
        }
        else
        {
            //THIS IS THE CODE WHICH IS RUN
            $finalisation->setFinaliseParAuteur(true);
            $this->em->flush();
            return (false);
        }
    }

Now is the problem :

when I search for $finalisation in the test, it appears that I dont get the object modified :

$finalisation = $em->getRepository(Finalisation::class)
        ->someMethodToGetTheFinalisationUpdated();

Proof : when i dump $finalisation, I got in dateCreation, and dateUpdate the same DateTime, which should not be the case, because the object was modified in the service by the function finalisationParAuteur.

I suspect the problem is from the two entities managers (one in the test, and the other in the service).

Any help whould be very much appreciated !

Thanks !


Solution

  • I found the solution after some struggle.

    Here is it, hope it will help someone else !

    When I call the service with entity manager, the $finalisation gets modified. And in the test, the $finalisation still points to the old version of the object.

    The solution is to use the refresh method (which I had never used before now) :

    $em->refresh($finalisation);
    

    This method refreshs the object, so I get the object with all modifications made in the service !