稍微夸大一下,这是我的 Romain Bruckert 和 Sash 的增强版本,它为您提供了这样的数组:
array:4 [▼
"ROLE_USER" => "User"
"ROLE_ALLOWED_TO_SWITCH" => "Allowed To Switch"
"ROLE_ADMIN" => "Admin (User, Allowed To Switch)"
"ROLE_SUPER_ADMIN" => "Super Admin (Admin (User, Allowed To Switch))"
]
这可以帮助您找到所有角色,包括特定角色:
我知道它的代码很多,它可以做得更好,但也许它可以帮助某人,或者你至少可以使用这段代码的片段。
/**
* Turns the role's array keys into string <ROLES_NAME> keys.
* @param array $rolesHierarchy
* @param bool $niceName
* @param bool $withChildren
* @param bool $withGrandChildren
* @return array
*/
protected static function flattenRoles($rolesHierarchy, $niceName = false, $withChildren = false, $withGrandChildren = false)
{
$flatRoles = [];
foreach ($rolesHierarchy as $key => $roles) {
if(!empty($roles)) {
foreach($roles as $role) {
if(!isset($flatRoles[$role])) {
$flatRoles[$role] = $niceName ? self::niceRoleName($role) : $role;
}
}
}
$flatRoles[$key] = $niceName ? self::niceRoleName($key) : $key;
if ($withChildren && !empty($roles)) {
if (!$recursive) {
if ($niceName) {
array_walk($roles, function(&$item) { $item = self::niceRoleName($item);});
}
$flatRoles[$key] .= ' (' . join(', ', $roles) . ')';
} else {
$childRoles = [];
foreach($roles as $role) {
$childRoles[$role] = $niceName ? self::niceRoleName($role) : $role;
if (!empty($rolesHierarchy[$role])) {
if ($niceName) {
array_walk($rolesHierarchy[$role], function(&$item) { $item = self::niceRoleName($item);});
}
$childRoles[$role] .= ' (' . join(', ', $rolesHierarchy[$role]) . ')';
}
}
$flatRoles[$key] .= ' (' . join(', ', $childRoles) . ')';
}
}
}
return $flatRoles;
}
/**
* Remove underscors, ROLE_ prefix and uppercase words
* @param string $role
* @return string
*/
protected static function niceRoleName($role) {
return ucwords(strtolower(preg_replace(['/\AROLE_/', '/_/'], ['', ' '], $role)));
}