【问题标题】:Check whether a node exists when validating config in Symfony2?在 Symfony2 中验证配置时检查节点是否存在?
【发布时间】:2014-06-26 10:24:32
【问题描述】:

我正在尝试验证 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();

但这对我也不起作用。

【问题讨论】:

    标签: validation symfony configuration yaml


    【解决方案1】:

    如果您将节点定义为必需且未在配置中定义,则会引发异常。

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

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

    【讨论】:

    • 好吧,这并不能解决我的问题,因为我不知道节点的名称。我需要检查配置中是否存在为另一个模块定义的模块。
    猜你喜欢
    • 2017-06-03
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多