【发布时间】:2019-09-10 10:12:01
【问题描述】:
我有一个 Symfony 4 项目,其中包含一个带有“角色”数组的用户实体(在我的数据库中的 JSON 中)。
/**
* @ORM\Column(type="json")
*/
private $roles = [];
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function addRole($role)
{
if (!in_array($role, $this->roles)) {
array_push($this->roles, $role);
}
return $this;
}
public function hasRole($role)
{
if (in_array($role, $this->roles)) {
return true;
}
return false;
}
public function removeRole($role)
{
if ($this->hasRole($role)) {
unset($this->roles[array_search($role, $this->roles)]);
}
return $this;
}
所以,我的User 角色可能类似于:
["ROLE_VALIDATEUR", "ROLE_SUPER_VALIDATEUR"]
但是,当我使用删除函数删除角色时,例如“ROLE_SUPER_VALIDATEUR”(因此,在那之后,我只有“ROLE_VALIDATEUR”角色),我的角色数组有时会像这样中断:
{"1" : "ROLE_VALIDATEUR"}
我的删除功能有什么问题?
【问题讨论】: