Symfony2 Config TreeBuilder验证YML中的数组值

时间:2012-11-22 15:02:20

标签: php validation symfony configuration

我在YML中有一个配置,如下所示:

foobar_template:
    templates:
        homepage:
            name: "Homepage template"
            regions: ["top", "main", "left", "bottom"]
            layout:
              - [ { region: "top", colspan: 4 } ]
              - [ { region: "left" }, { region: "main", colspan: 3 } ]
              - [ { region: "bottom", colspan: 4 } ]

        subpage:
            name: "Subpage template"
            regions: ["top", "main"]
            layout:
              - [ { region: "top", colspan: 4 } ]
              - [ { region: "main", colspan: 4 } ]

我一直在努力确保根据规范定义此配置,但似乎无法确保布局部分包含至少定义一个区域的条目。目前我的Configuration.php包含以下内容:

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('foobar_template');

        $rootNode
            ->children()
                ->arrayNode('templates')
                    ->useAttributeAsKey('template')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('name')->end()
                            ->arrayNode('regions')
                                ->isRequired()
                                ->requiresAtLeastOneElement()
                                ->prototype('scalar')->end()
                            ->end()
                            ->append($this->addLayoutNode())
                        ->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }

    public function addLayoutNode()
    {
        $builder = new TreeBuilder();
        $node = $builder->root('layout');

        $node
            ->isRequired()
            ->requiresAtLeastOneElement()
            ->prototype('array')
                ->prototype('variable')->end()
            ->end();

        return $node;
    }
}

但我真的想测试指定的布局块是否包含一个区域(即至少包含- [{ region: <region_name> }]的片段,那么我应该在addLayoutNode()中使用什么而不是->prototype('variable')->end()来实际执行此测试?我尝试了多项内容,但在尝试执行此操作时总会遇到InvalidDefinitionException或InvalidConfigurationException。任何人都知道如何在Configuration中测试上述内容?(我目前在负载中进行了一些完整性检查bundle Extension,但如果Configuration可以检查这个就更清晰了。

1 个答案:

答案 0 :(得分:-2)

您可以使用ConfigurationProccesor:http://symfony.com/doc/2.0/components/config/definition.html#processing-configuration-values 或者用于更复杂配置的CompilerPass。