为了正确表示您的角色,您需要递归。角色可以扩展其他角色。
我在 security.yml 中使用以下角色作为示例:
ROLE_SUPER_ADMIN: ROLE_ADMIN
ROLE_ADMIN: ROLE_USER
ROLE_TEST: ROLE_USER
您可以通过以下方式获得此角色:
$originalRoles = $this->getParameter('security.role_hierarchy.roles');
递归示例:
private function getRoles($originalRoles)
{
$roles = array();
/**
* Get all unique roles
*/
foreach ($originalRoles as $originalRole => $inheritedRoles) {
foreach ($inheritedRoles as $inheritedRole) {
$roles[$inheritedRole] = array();
}
$roles[$originalRole] = array();
}
/**
* Get all inherited roles from the unique roles
*/
foreach ($roles as $key => $role) {
$roles[$key] = $this->getInheritedRoles($key, $originalRoles);
}
return $roles;
}
private function getInheritedRoles($role, $originalRoles, $roles = array())
{
/**
* If the role is not in the originalRoles array,
* the role inherit no other roles.
*/
if (!array_key_exists($role, $originalRoles)) {
return $roles;
}
/**
* Add all inherited roles to the roles array
*/
foreach ($originalRoles[$role] as $inheritedRole) {
$roles[$inheritedRole] = $inheritedRole;
}
/**
* Check for each inhered role for other inherited roles
*/
foreach ($originalRoles[$role] as $inheritedRole) {
return $this->getInheritedRoles($inheritedRole, $originalRoles, $roles);
}
}
输出:
array (
'ROLE_USER' => array(),
'ROLE_TEST' => array(
'ROLE_USER' => 'ROLE_USER',
),
'ROLE_ADMIN' => array(
'ROLE_USER' => 'ROLE_USER',
),
'ROLE_SUPER_ADMIN' => array(
'ROLE_ADMIN' => 'ROLE_ADMIN',
'ROLE_USER' => 'ROLE_USER',
),
)