Symfony2:在FormBuilder中获取用户角色列表


Symfony2: Getting the list of user roles in FormBuilder

我正在制作一个用于创建用户的表单,我想在创建用户时为用户提供一个或多个角色。

如何获取 security.yml 中定义的角色列表?

这是我目前的表单构建器:

public function buildForm(FormBuilder $builder, array $options)
{
    parent::buildForm($builder, $options);
    // add your custom fields
    $user = new User();
    $builder->add('regionUser');
    $builder->add('roles' ,'choice' ,array('choices' => $user->getRolesNames(),
            'required'  => true,
    ));
}

和用户.php

public function getRolesNames(){
    return array(
        "ADMIN" => "Administrateur",
        "ANIMATOR" => "Animateur",
        "USER" => "Utilisateur",        
    );
}

当然,此解决方案不起作用,因为roles在数据库中定义为位图,因此无法创建choices列表。

提前谢谢。

security.role_hierarchy.roles容器参数将角色层次结构保存为数组。您可以概括它以获取定义的角色列表。

您可以从此方法获取可访问角色的列表:

Symfony'Component'Security'Core'Role'RoleHierarchy::getReachableRoles(array $roles)

它似乎返回可从数组$roles参数中的角色访问的所有角色。它是Symfony的内部服务,其ID是security.role_hierarchy的,不是公开的(你必须明确地将其作为参数传递,它不能从服务容器中获取)。

为了正确表示您的角色,您需要递归。角色可以扩展其他角色。

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

您可以为此创建一个服务并注入"security.role_hierarchy.roles"参数。

服务定义:

acme.user.roles:
   class: Acme'DemoBundle'Model'RolesHelper
   arguments: ['%security.role_hierarchy.roles%']

服务等级:

class RolesHelper
{
    private $rolesHierarchy;
    private $roles;
    public function __construct($rolesHierarchy)
    {
        $this->rolesHierarchy = $rolesHierarchy;
    }
    public function getRoles()
    {
        if($this->roles) {
            return $this->roles;
        }
        $roles = array();
        array_walk_recursive($this->rolesHierarchy, function($val) use (&$roles) {
            $roles[] = $val;
        });
        return $this->roles = array_unique($roles);
    }
}

您可以像这样在控制器中获取角色:

$roles = $this->get('acme.user.roles')->getRoles();

在Symfony 3.3中,你可以创建一个RolesType.php如下所示:

<?php
namespace AppBundle'Form'Type;
use Symfony'Component'Form'AbstractType;
use Symfony'Component'OptionsResolver'OptionsResolver;
use Symfony'Component'Form'Extension'Core'Type'ChoiceType;
use Symfony'Component'Security'Core'Role'RoleHierarchyInterface;
/**
 * @author Echarbeto
 */
class RolesType extends AbstractType {
  private $roles = [];
  public function __construct(RoleHierarchyInterface $rolehierarchy) {
    $roles = array();
    array_walk_recursive($rolehierarchy, function($val) use (&$roles) {
      $roles[$val] = $val;
    });
    ksort($roles);
    $this->roles = array_unique($roles);
  }
  public function configureOptions(OptionsResolver $resolver) {
    $resolver->setDefaults(array(
        'choices' => $this->roles,
        'attr' => array(
            'class' => 'form-control',
            'aria-hidden' => 'true',
            'ref' => 'input',
            'multiple' => '',
            'tabindex' => '-1'
        ),
        'required' => true,
        'multiple' => true,
        'empty_data' => null,
        'label_attr' => array(
            'class' => 'control-label'
        )
    ));
  }
  public function getParent() {
    return ChoiceType::class;
  }
}

然后将其添加到表单中,如下所示:

$builder->add('roles', RolesType::class,array(
          'label' => 'Roles'
      ));

重要的是还必须包含每个角色,例如:ROLE_ADMIN: [ROLE_ADMIN, ROLE_USER]

如果需要获取特定角色的所有继承角色:

use Symfony'Component'Security'Core'Role'Role;
use Symfony'Component'Security'Core'Role'RoleHierarchy;
private function getRoles($role)
{
    $hierarchy = $this->container->getParameter('security.role_hierarchy.roles');
    $roleHierarchy = new RoleHierarchy($hierarchy);
    $roles = $roleHierarchy->getReachableRoles([new Role($role)]);
    return array_map(function(Role $role) { return $role->getRole(); }, $roles);
}

然后调用此函子:$this->getRoles('ROLE_ADMIN');

在Symfony 2.7中,在控制器中,你必须使用$this->getParameters()来获取角色:

$roles = array();
foreach ($this->getParameter('security.role_hierarchy.roles') as $key => $value) {
    $roles[] = $key;
    foreach ($value as $value2) {
        $roles[] = $value2;
    }
}
$roles = array_unique($roles);

这不是你想要的,但它使你的示例有效:

use Vendor'myBundle'Entity'User;
public function buildForm(FormBuilder $builder, array $options)
{
    parent::buildForm($builder, $options);
    // add your custom fields
    $user = new User();
    $builder->add('regionUser');
    $builder->add('roles' ,'choice' ,array('choices' => User::getRolesNames(),
            'required'  => true,
    ));
}

但是关于从实体获取角色,也许您可以使用实体存储库的内容来查询数据库。

下面是一个使用 queryBuilder 获取所需内容到实体存储库中的很好示例:

public function buildForm(FormBuilder $builder, array $options)
{
    parent::buildForm($builder, $options);
    // add your custom fields
    $user = new User();
    $builder->add('regionUser');
    $builder->add('roles' ,'entity' array(
                 'class'=>'Vendor'MyBundle'Entity'User',
                 'property'=>'roles',
                 'query_builder' => function ('Vendor'MyBundle'Entity'UserRepository $repository)
                 {
                     return $repository->createQueryBuilder('s')
                            ->add('orderBy', 's.sort_order ASC');
                 }
                )
          );
}

http://inchoo.net/tools-frameworks/symfony2-entity-field-type/

这是我所做的:

表格类型:

use FTW'GuildBundle'Entity'User;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('username')
        ->add('email')
        ->add('enabled', null, array('required' => false))
        ->add('roles', 'choice', array(
        'choices' => User::getRoleNames(),
        'required' => false,'label'=>'Roles','multiple'=>true
    ))
        ->add('disableNotificationEmails', null, array('required' => false));
}

在实体中:

use Symfony'Component'Yaml'Parser; ...
static function getRoleNames()
{
    $pathToSecurity = __DIR__ . '/../../../..' . '/app/config/security.yml';
    $yaml = new Parser();
    $rolesArray = $yaml->parse(file_get_contents($pathToSecurity));
    $arrayKeys = array();
    foreach ($rolesArray['security']['role_hierarchy'] as $key => $value)
    {
        //never allow assigning super admin
        if ($key != 'ROLE_SUPER_ADMIN')
            $arrayKeys[$key] = User::convertRoleToLabel($key);
        //skip values that are arrays --- roles with multiple sub-roles
        if (!is_array($value))
            if ($value != 'ROLE_SUPER_ADMIN')
                $arrayKeys[$value] = User::convertRoleToLabel($value);
    }
    //sort for display purposes
    asort($arrayKeys);
    return $arrayKeys;
}
static private function convertRoleToLabel($role)
{
    $roleDisplay = str_replace('ROLE_', '', $role);
    $roleDisplay = str_replace('_', ' ', $roleDisplay);
    return ucwords(strtolower($roleDisplay));
}

请提供反馈...我已经使用了其他答案中的一些建议,但我仍然觉得这不是最好的解决方案!

//FormType
use Symfony'Component'Yaml'Parser;
function getRolesNames(){
        $pathToSecurity = /var/mydirectory/app/config/security.yml
        $yaml = new Parser();
        $rolesArray = $yaml->parse(file_get_contents($pathToSecurity ));
        return $rolesArray['security']['role_hierarchy']['ROLE_USER'];
}

到目前为止,这是我发现从配置文件中获取或设置我想要的内容的最佳方法。

勇气