With auto wiring enabled, you can also directly inject the RoleHierarchy
object filled with the global role hierarchy.
Simply inject the RoleHierarchyInterface
in your controller or service by using dependency injection:
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
public function __construct(RoleHierarchyInterface $roleHierarchy)
{
$this->roleHierarchy = $roleHierarchy;
}
Note: This also allows you to call getReachableRoles()
on the RoleHierarchy
object, which could be useful in your case:
use Symfony\Component\Security\Core\Role\Role;
$this->roleHierarchy->getReachableRoles([new Role('ROLE_USER')]);
$this->roleHierarchy->getReachableRoleNames(['ROLE_USER']); // Symfony 5+
As of Symfony4 you have to add an alias for security.role_hierarchy
in your config/services.yml
by adding the following line:
services:
# creating alias for RoleHierarchyInterface
Symfony\Component\Security\Core\Role\RoleHierarchyInterface: '@security.role_hierarchy'