Symfony2: Getting the list of user roles in FormBuilder

前端 未结 10 1396
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 15:55

I\'m making a form for user creation, and I want to give one or several roles to a user when I create him.

How do I get the list of roles defined in security.y

10条回答
  •  既然无缘
    2020-12-08 16:47

    For a correct representation of your roles, you need recursion. Roles can extend other roles.

    I use for the example the folowing roles in security.yml:

    ROLE_SUPER_ADMIN: ROLE_ADMIN
    ROLE_ADMIN:       ROLE_USER
    ROLE_TEST:        ROLE_USER
    

    You can get this roles with:

    $originalRoles = $this->getParameter('security.role_hierarchy.roles');
    

    An example with recursion:

    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);
        }
    }
    

    The output:

    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',
      ),
    )
    

提交回复
热议问题