Symfony2 SyliusRbacBundle role asigment error: Invalid argument supplied for foreach() NestedSetRolesResolver.php

Symfony2 SyliusRbacBundle role asigment error: Invalid argument supplied for foreach() NestedSetRolesResolver.php

我正在实施 SyliusRbacBundle 和 FOSUserBundle,我设置了一个安全区域只是为了测试是否一切正常,但是当我浏览到该路线时出现以下错误:

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

当通过 FosUserBundle 创建用户时,列 'authorization_roles' 填充了以下信息:

Doctrine\Common\Collections\ArrayCollection@00000000318556cb000000002fabcd7d

我收到那个错误并不奇怪,它不是预期的数组或 ArrayCollection。因此,我没有正确分配角色,但我不确定如何在创建用户或提升用户时执行此操作。这是我的用户模型的样子:

/**
 * 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;
}
}

我在这里查看了他们是如何做到的:https://github.com/Sylius/Sylius/blob/master/src/Sylius/Component/Core/Model/User.php

我被困在那里,任何见解将不胜感激。

谢谢!

事实证明我没有正确添加关系,所以我没有用户和角色之间的中间人 table。我添加了如下注释:

    /**
     * @var
     *
     * @ORM\ManyToMany(targetEntity="Sylius\Component\Rbac\Model\RoleInterface")
     * @ORM\JoinTable(name="sylius_user_role",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false, onDelete="CASCADE")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id", unique=true, nullable=false, onDelete="CASCADE")}
     *      )
     */
    private $authorizationRoles;

然后更新数据库,覆盖 FOSUserBundle 配置文件编辑表单,现在一切正常。