【问题标题】:Not able to parse correctly a yaml file with symfony TreeNode无法使用 symfony TreeNode 正确解析 yaml 文件
【发布时间】:2014-07-19 06:49:33
【问题描述】:

我正在尝试做一些看似简单的事情。

我要解析这个yaml结构:

  filters:
    filter:
      class: ParentNamespace\MyClassA
    filter:
      class: ParentNamespace\MyClassB
      params:
        customParam: 5
        anotherParam: 1

所以,我想要一个必需的过滤器节点,它本身可以有 1 个或多个过滤器节点。然后每个节点都必须有一个“类”节点并有一个可选的参数数组节点。

我正在尝试使用这个 TreeBuilder,但它只采用第二个过滤器,我想知道是否覆盖了第一个。

我尝试了所有方法,但无法正常工作。

->arrayNode('filters')
    ->isRequired()
    ->children()
        ->arrayNode('filter')
            ->children()
                ->scalarNode('class')
                    ->isRequired()
                ->end()
                ->arrayNode('params')
                    ->defaultValue(array())
                    ->prototype('variable')->end()
                ->end()
            ->end()
        ->end()
    ->end()
->end()

【问题讨论】:

    标签: php parsing symfony yaml config


    【解决方案1】:

    您忘记将filter 节点设为原型数组节点。现在它正在覆盖自身,因为 ArrayNode 只能出现一次:

    ->arrayNode('filters')
        ->isRequired()
        ->children()
            ->arrayNode('filter')
                ->prototype('array')
                    ->children()
                        ->scalarNode('class')
                            ->isRequired()
                        ->end()
                        ->arrayNode('params')
                            ->defaultValue(array())
                            ->prototype('variable')->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ->end()
    ->end()
    

    除此之外,我建议你改用这样的东西:

    filters:
      ParentNamespace\MyClassA: ~
      ParentNamespace\MyClassB:
        params:
          customParam: 5
          anotherParam: 1
    

    它更加友好,并且允许您支持 XML:

    ->fixXmlConfig('filter')
    ->children()
        ->arrayNode('filters')
            ->useAttributeAsKey('class')
            ->prototype('array')
                ->children()
                    ->arrayNode('params')
                        ->defaultValue(array())
                        ->prototype('variable')->end()
                    ->end()
                ->end()
            ->end()
        ->end()
    ->end()
    

    最后,我建议您使用requiresAtLeastOneElement() 而不是isRequired() 来要求至少一个元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-10
      • 2020-10-14
      • 2020-07-18
      • 1970-01-01
      • 2014-07-19
      相关资源
      最近更新 更多