How to retrieve full role hierarchy in Symfony

You can get the hierarchy from the container:

$container->getParameter('security.role_hierarchy.roles')

Symfony 5 answer

namespace App\Controller;

...
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchy;

class UserController extends AbstractController
{
    private $roleHierarchy;

    /**
     * @Route("/users", name="users")
     */
    public function usersIndex(RoleHierarchyInterface $roleHierarchy)
    {
        $this->roleHierarchy = $roleHierarchy;

        // your user service or your Doctrine code here
        $users = ...

        foreach ($users as $user) {
            if ($this->isGranted($user, 'ROLE_SUPER_ADMIN')) {
                ...
            }
        }
        ...
    }

    private function isGranted(User $user, string $role): bool 
    {
        $reachableRoles = $this->roleHierarchy->getReachableRoleNames($user->getRoles());

        foreach ($reachableRoles as $reachableRole) {
            if ($reachableRole === $role) {
                return true;
            }
        }

        return false;
    }
}

Note: I put everything in the controller for the sake of simplicity here, but of course I'd recommend to move the Role Management code into your own dedicated role service.


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'

Tags:

Symfony