1

Good evening,

I recently upgraded to symfony 2.7.6. Beside it helped me to setup the HWIOAuthBundle, i noticed a bug in a template that was doing well before.

The following test is never valid, although I'm connected as the creator of this event!

{% if event.getCreator() == app.user %}

Creator looks like this :

class Event implements EventInterface
{

/**
 * @ORM\ManyToOne(targetEntity="FS\UserBundle\Entity\User", cascade={"persist"}, fetch="EAGER")
 *
 * @ORM\JoinColumn(referencedColumnName="id", nullable=false, onDelete="CASCADE")
 */
private $creator;

public function getCreator()
{
    return $this->creator;
}
...

I started searching in the profiler and discovered the Twig_ExtensionInterface::getGlobals() and Twig_ExtensionInterface::initRuntime() are deprecated in Symfony 2.7.6 (in my application).

Then i read a post from Twig developper Remi Collet, saying that these 2 deprecated calls can make Twig test fail, and uploaded a simple patch for twig (v1.23), but this patch didn't help.

I took an older version of twig/twig, which helped me solve the deprecated method warning. But the app.user test is still broken...

Anybody has an idea why my global extension, app.user can't be compared with another user in twig ?

Louis
  • 25
  • 6

1 Answers1

1

It has nothing to do with the deprecation warnings. They only exist to inform you that your code might not work with future versions, but in the current one everything’s still fine.

The problem is that you can have more than one user object containing data of the same user. If you only use Doctrine, it will give you the same object for a user every time you ask for it. That’s why you can sometimes compare objects.

But the session management (that provides app.user) might not necessarily rely on Doctrine. For performance purposes, it may store the object in some other way, like in the session itself.

So now you have two user objects for the same user: one from session management and one from Doctrine (event.getCreator()). And if you compare these two objects, PHP will of course find that those are two different objects (even though they contain the same data) and return false on that comparison.

A solution might be to check for a scalar value in the user objects, like app.user.getId() == event.getCreator().getId() or something like that. This way you are comparing values instead of instances.

hanzi
  • 2,877
  • 18
  • 26
  • Thanks a lot ! I was sure that in Symfony two objects reffering to the same entity would valid the '==' test. – Louis Nov 05 '15 at 04:00
  • Yep, and Symfony and Doctrine do a very fine job on giving you the impression that an entity object is always mapped to a database entry. But it’s exceptions like these where you still notice the internal workings. – hanzi Nov 05 '15 at 04:03