【问题标题】:How to deep merge arrayPrototype in SymfonyConfiguration如何在 SymfonyConfiguration 中深度合并 arrayPrototype
【发布时间】:2020-10-16 11:57:43
【问题描述】:

我有以下配置:

        $treeBuilder = new TreeBuilder('rest_api');
        $treeBuilder->getRootNode()
            ->addDefaultsIfNotSet()
            ->children()
                ->arrayNode('exceptions')
                    ->defaultValue([])
                    ->arrayPrototype()
                        ->scalarPrototype()
                        ->end()
                    ->end()
                ->end()
            ->end();

以下是 2 个不同捆绑包中的 2 个文件:

rest_api:
  exceptions:
    404:
      - UserNotFoundException
    400:
      - InvalidCredentailsException
rest_api:
  exceptions:
    404:
      - NotFoundHttpException
    400:
      - SomeRandomException
      - OtherRandomException

我希望结果如下所示:

^ array:1 [
  "exceptions" => array:4 [
    404 => array:1 [
      0 => "NotFoundHttpException"
      1 => "UserNotFoundException"
    ]
    400 => array:2 [
      0 => "SomeRandomException"
      1 => "OtherRandomException"
       => "InvalidCredentailsException"
    ]
  ]
]

但是我得到了这个:

^ array:1 [
  "exceptions" => array:4 [
    404 => array:1 [
      0 => "NotFoundHttpException"
    ]
    400 => array:2 [
      0 => "SomeRandomException"
      1 => "OtherRandomException"
    ]
    405 => array:1 [
      0 => "UserNotFoundException"
    ]
    406 => array:1 [
      0 => "InvalidCredentailsException"
    ]
  ]
]

如何启用 arrayPrototypes 的深度合并?

我尝试同时使用整数和字符串作为键名,将键更改为非数字:c404c400,以及文档中的两种设置:performNoDeepMergingcannotBeOverwritten,但似乎都不起作用.

我需要的是 performDeepMerging 选项或类似的东西,但我在任何地方都看不到它。

【问题讨论】:

    标签: symfony configuration


    【解决方案1】:

    默认情况下,arrayNode 被视为具有数字索引的列表。要强制将其视为关联数组,您可以使用useAttributeAsKey 定义它。只需传递一个虚拟字段名称即可,不会引发错误。

    // ...
    ->arrayNode('exceptions')
        ->defaultValue([])
        ->useAttributeAsKey('name')
    // ...
    

    this GitHub comment 中有一些很好的例子说明数组节点处理方式的不同。

    【讨论】:

      猜你喜欢
      • 2020-08-28
      • 2017-02-21
      • 2015-03-12
      • 2021-03-13
      • 2020-11-12
      • 1970-01-01
      相关资源
      最近更新 更多