Symfony2: Call to a member function toArray() on a non-object

2.9k views Asked by At

Hy,

I've a short question about a weird error message I get on my Symfony 2 project.

I've an entity class User which retrieves its roles via Doctrine. This works perfectly! But...

I want let the User implement EquatableInterface, so I've added the User::isEqualTo method. This is where my error occurs. This line, especially $this->getRoles()is causing the error:

Symfony2: Call to a member function toArray() on a non-object

But the same toArray function usage inside User::getRoles() works great on the rest of the project. So I don't get what's wrong here.

Can somebody help me with it? Any help appreciated!

Update 1

Looking into the logs and using your current help, here are some insights:

  • $thisin getRoles always returns the entity user class, so nothing special there, but
  • After each isEqualTocall, $this->rolesreturns null, after that it doesn't.

Update 2

Here are my further insights:

  • I've added Konstantin's is_nullcheck, but it doesn't solve the actual problem.
  • As I could see in the logs during logging in, refreshUser is called and everything is perfect. Roles are found. After refreshUser isEqualTois fired and suddenly $this->rolesbecomes null and get_class($this->roles)returns user entity class (?!?!?) in comparison to Doctrine\\ORM\\PersistentCollection.

When I add the roles to the user's (un)serialize methods everything seems to be fine inside this isEqualTo method. He finally is grabbing the roles and I can add my logic to it. Fine! But afterwards Symfony is throwing erros like this or that. In my pov it has something to do with the serialization.

After some readings I've added serialization to the role entity because this seems the standard way to go. Serializing the user and the roles on their own, not (un)serializing the roles inside the user class. But as soon as I'm removing the roles from the user's serializing methods the old problem occurs again and again concerning $this->roles is always null when isEqualTo is fired. Everytime before and after everything's great, except this method call.

I haven't any clue what's exactly going wrong here.

Any idea?

1

There are 1 answers

1
Konstantin Pereiaslov On

Most likely this is caused by $this->roles being not populated at the moment of getRoles() call. It's hard to say what exactly is causing it without going through your other code. An easy solution would be to add a check to your getRoles() method at line 138:

if ($this->roles === null) {
     return null;
}

But I'm not sure that's what you want to do, you probably want to figure out why roles are actually empty at that moment.