I am implementing SyliusRbacBundle along with FOSUserBundle, I set a secure area just to test if every thing is working but when I browse to that route I got a the following error:
CRITICAL - Uncaught PHP Exception Symfony\Component\Debug\Exception\ContextErrorException: "Warning: Invalid argument supplied for foreach()" at /home/daniel/web/tests/tmootb/vendor/sylius/rbac/Resolver/NestedSetRolesResolver.php line 48
When the user is created via FosUserBundle column 'authorization_roles' is filled with this information:
Doctrine\Common\Collections\ArrayCollection@00000000318556cb000000002fabcd7d
Not a big surprise I got that error, that's not an array or ArrayCollection as expected. So, I am not assigning the roles correctly but I am not sure how to do it upon user creation or user promotion. Here is how my User model looks like:
/**
* Class User
* @package App\AppBundle\Entity
* @ORM\Entity
* @ORM\Table(name="users")
*/
class User extends BaseUser implements IdentityInterface
{
/**
* @var
*
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var
*
* @ORM\Column(type="string")
*/
private $authorizationRoles;
public function __construct()
{
parent::__construct();
$this->authorizationRoles = new ArrayCollection();
}
/**
* Get roles.
*
* @return RoleInterface[]
*/
public function getAuthorizationRoles()
{
return $this->authorizationRoles;
}
/**
* {@inheritdoc}
*/
public function addAuthorizationRole(RoleInterface $role)
{
if (!$this->hasAuthorizationRole($role)) {
$this->authorizationRoles->add($role);
}
}
/**
* {@inheritdoc}
*/
public function removeAuthorizationRole(RoleInterface $role)
{
if ($this->hasAuthorizationRole($role)) {
$this->authorizationRoles->removeElement($role);
}
}
/**
* {@inheritdoc}
*/
public function hasAuthorizationRole(RoleInterface $role)
{
return $this->authorizationRoles->contains($role);
}
/**
* {@inheritdoc}
*/
public function getRoles()
{
$roles = parent::getRoles();
foreach ($this->getAuthorizationRoles() as $role) {
$roles = array_merge($roles, $role->getSecurityRoles());
}
return $roles;
}
}
I had a look at how they do it here: https://github.com/Sylius/Sylius/blob/master/src/Sylius/Component/Core/Model/User.php
I am stuck there, any insight would be greatly appreciated.
Thanks!
Turn out that I wasn't adding the relationship properly, so I haven't had the intermediate table between users and roles. I added the annotations as follow:
Then updated the database, override the FOSUserBundle profile edit form, and everything is working now.