在Symfony2中验证配置时是否存在节点?

时间:2014-06-26 10:24:33

标签: validation symfony configuration yaml

我试图在YAML中验证配置:

parameters:
    modules:
        spu-module:
            path:
            requires: ['spw-module']
        spw-module:
            path:
            requires: []

使用此代码:

$rootNode
    ->children()
        ->arrayNode('modules')
            ->isRequired()
            ->prototype('array')
                ->children()
                    ->arrayNode('requires')
                        ->prototype('scalar')->end()
                    ->end()
                    ->scalarNode('path')->isRequired()->end()
                ->end()
            ->end()
        ->end()
    ->end()
->end();

我尝试测试的是检查当前配置中是否存在requires:中定义的必需模块。我怎么能这样做?

更新 我试着做这样的事情:

$rootNode
    ->children()
        ->arrayNode('modules')
            ->isRequired()
            ->prototype('array')
                ->children()
                    ->arrayNode('requires')
                        ->prototype('scalar')
                            ->validate()
                                ->always(function ($v) use ($rootNode) {
                                    if (preg_match('/(spw-)(?:[a-z][a-z0-9_]*)/is', $v)) {
                                        $rootNode
                                            ->children()
                                                ->arrayNode('yui/modules')
                                                    ->children()
                                                        ->arrayNode($v)
                                                            ->isRequired()
                                                            ->cannotBeEmpty()
                                                        ->end()
                                                    ->end()
                                                ->end()
                                            ->end()
                                        ->end();
                                    }
                                })
                            ->end()
                        ->end()
                    ->end()
                    ->scalarNode('path')->isRequired()->end()
                ->end()
            ->end()
        ->end()
    ->end()
->end();

但它对我来说也不起作用。

1 个答案:

答案 0 :(得分:0)

如果您将Node定义为Required并且未在configs中定义,则会抛出异常。

您是否要定义在requires节点中定义至少一个元素:

->arrayNode('requires')
        ->isRequired()
        ->requiresAtLeastOneElement()