faz*_*azy 2 php configuration symfony
我正在使用Symfony2的树构建器,我看到它有一些基本的验证规则,如下所述:http://symfony.com/doc/current/components/config/definition.html#validation-rules
有没有办法通过正则表达式进行验证?
这是我现在正在做的事情,但我不确定这是否是"最佳做法".我要验证的配置项是root_node.
config.yml
my_bundle:
root_node: /some/path # this one is valid
Run Code Online (Sandbox Code Playgroud)
的configuration.php
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('my_bundle');
$rootNode
->children()
->scalarNode('root_node')
->end()
->end()
->end();
return $treeBuilder;
Run Code Online (Sandbox Code Playgroud)
MyBundleExtension.php
$nodePattern = '#/\w+(/w+)*#';
if (! preg_match($nodePattern, $config['root_node'])) {
throw new \Exception("root_node is not valid: must match the pattern: $nodePattern");
}
Run Code Online (Sandbox Code Playgroud)
所以,我真正追求的是TreeBuilder方法:
->validate()->ifNotMatchesRegex()->thenInvalid()
Run Code Online (Sandbox Code Playgroud)
或者,如果没有,那就是执行我的验证规则的最佳方法.
您可以做的是将该ifTrue方法与自定义函数一起使用.像这样的东西:
$rootNode
->children()
->scalarNode('root_node')
->validate()
->ifTrue(function ($s) {
return preg_match('#/\w+(/\w+)*#', $s) !== 1;
})
->thenInvalid('Invalid path')
->end()
->end()
->end();
Run Code Online (Sandbox Code Playgroud)
请注意我对你的正则表达式做的细微修改.
| 归档时间: |
|
| 查看次数: |
622 次 |
| 最近记录: |