引用分布式配置中的非参数条目



这是我昨天问的在config.yml中引用非参数条目问题的后续。

假设我们有更复杂的情况,其中每个实体都有一个 .yml 配置文件。在每个设置中,security.role_hierarchy设置具有与该实体相关的角色层次结构。这样:

#user.yml
security:
    role_hierarchy: &srh
        ROLE_USER_SHOW: ~
        ROLE_USER_LIST: ~
        ROLE_USER_NEW: ~
        ROLE_USER_EDIT_OWN: ~
        ROLE_USER_EDIT: ROLE_USER_EDIT_OWN
        ROLE_USER_SOFTDELETE_OWN: ~
        ROLE_USER_SOFTDELETE: ROLE_USER_SOFTDELETE_OWN
        ROLE_USER_DELETE: ~
        ROLE_USER_FLAG: ~
        ROLE_USER_ALL:
            - ROLE_USER_SHOW
            - ROLE_USER_LIST
            - ROLE_USER_NEW
            - ROLE_USER_EDIT
            - ROLE_USER_DELETE
            - ROLE_USER_SOFTDELETE
            - ROLE_USER_FLAG
#group.yml
security:
    role_hierarchy: &srh
        ROLE_GROUP_SHOW: ~
        ROLE_GROUP_LIST: ~
        ROLE_GROUP_NEW: ~
        ROLE_GROUP_EDIT: ~
        ROLE_GROUP_DELETE: ~
        ROLE_GROUP_ALL:
            - ROLE_GROUP_SHOW
            - ROLE_GROUP_LIST
            - ROLE_GROUP_NEW
            - ROLE_GROUP_EDIT
            - ROLE_GROUP_DELETE
easy_admin:
    entities:
        Group:
            form:
                fields:
                    - 
                      property: 'roles' 
                      type: choice
                      type_options: 
                          expanded: true
                          multiple: true
                          choices: *srh

但是提出的解决方案仅将choices链接到group.yml中的security.role_hierarchy,因此它仅引用ROLE_GROUP_*角色。我希望choices提供合并值security.role_hierarchy以便它具有ROLES_USER_*ROLES_GROUP_*和所有其他定义的角色。

这可能吗?

所以我设法自己做了。正如@Anthon所说,&*在这里毫无用处。我们必须通过Symfony来做到这一点。方法如下:

我使用security.role_hierarchy作为定义安全层次结构的可合并点 - 以及应用程序中使用的角色列表。我将选择字段保留未定义的选项,如下所示:

            - 
              property: 'roles' 
              type: choice
              type_options: 
                  expanded: true
                  multiple: true

然后我在控制器中使用一种方法来设置选项:

// AppBundle/Controller/AdminController.php
public function indexAction(Request $request)
{
    $choices = [];$preferred = [];
    $vals = array_keys($this->container->getParameter('security.role_hierarchy.roles'));
    $choices = $vals;
    // actually there is some beautifying of $choices but it's not that important
    // get $formBuilder and...
    $formBuilder->add('roles', ChoiceType::class, ['choices'=>array_combine($choices, $vals), 'multiple'=>true, 'expanded'=>false]);
    return $formBuilder;
}

我放弃了$formBuilder创建,因为我以适合 EasyAdmin 的方式进行了创建,因此在其他情况下会有另一种方法可以做到这一点。

可能还有另一种方法可以做到这一点,但它很混乱:在控制器中获取security.role_hierarchy,根据需要处理它,然后将其分配给 Twig 全局变量:

// AppBundle/Controller/AdminController.php
public function indexAction(Request $request)
{
    $vals = array_keys($this->container->getParameter('security.role_hierarchy.roles'));
    $this->container->get('twig')->addGlobal("_security_roles", $vals);
    // ...
}

然后更新相应的 Twig 模板。

但我不喜欢不必要的全局变量,所以没有对其进行广泛测试。

最新更新