in_array() expects parameter 2 to be array, null given

Gianni Alessandro picture Gianni Alessandro · Jan 24, 2014 · Viewed 45.5k times · Source

I made a web-application with Symfony2, and I'm using PUGX User Bundle and FosUserBundle to manage 2 different users.

This is one of the two user:

  /**
   * @ORM\Entity
   * @ORM\Table(name="user_Operator")
   * @ORM\HasLifecycleCallbacks()
   * @UniqueEntity(fields = "username", targetClass = "Acme\ManagementBundle\Entity\User", message="Username already_used")
   * @UniqueEntity(fields = "email", targetClass = "Acme\ManagementBundle\Entity\User", message="Email already_used")
   */
  class UserOperator extends User
  {
      /**
       * @ORM\Id
       * @ORM\Column(type="integer")
       * @ORM\GeneratedValue(strategy="AUTO")
       */
      protected $id;

          /**
       * @ORM\PrePersist
       */
      public function setCreatedAtValue()
      {
          $this->addRole('ROLE_OPERATOR');
      }    
  }

When I try to register, I fill the form, submit, than appears:

Warning: in_array() expects parameter 2 to be array, null given in C:\BitNami\wampstack-
5.4.23-0\frameworks\symfony\vendor\friendsofsymfony\user-    
bundle\FOS\UserBundle\Model\User.php line 142

The line 142 is the following:

   135    public function addRole($role)
          {
              $role = strtoupper($role);
              if ($role === static::ROLE_DEFAULT) {
                  return $this;
              }

   142        if (!in_array($role, $this->roles, true)) {
                  $this->roles[] = $role;
              }

              return $this;
          }

Don't know because I have this problem since I made an association @ORM\ManyToMany between User and Mission, that is another entity that here doesn't appear. Before this I hadn't this problem.

I use PUGXUser Bundle because it helps to easily manage two different kind of user. The User Entity is in my bundle, extends FosUserBundle..../Model/User.php and is extended by UserOperator and UserGroundStation.

The definition of the role is in the FosUserBundle.../Model/User.php:

/**
 * @var array
 */
protected $roles;

and the costruct is:

public function __construct()
{
    $this->roles = array();
}

Answer

Victor Bocharsky picture Victor Bocharsky · Jan 24, 2014

Try to use:

if (is_array($this->roles)) {
    if (!in_array($role, $this->roles, true)) {
        $this->roles[] = $role;
    }
}