gre*_*emo 15 configuration dependency-injection symfony symfony-2.1
我的配置节点可以source同时支持string和array值吗?
采购自string:
# Valid configuration 1
my_bundle:
source: %kernel.root_dir%/../Resources/config/source.json
Run Code Online (Sandbox Code Playgroud)
采购自array:
# Valid configuration 2
my_bundle:
source:
operations: []
commands: []
Run Code Online (Sandbox Code Playgroud)
扩展类可以区分它们:
if (is_array($config['source']) {
// Bootstrap from array
} else {
// Bootstrap from file
}
Run Code Online (Sandbox Code Playgroud)
我可能会使用这样的东西:
$rootNode->children()
->variableNode('source')
->validate()
->ifTrue(function ($v) { return !is_string($v) && !is_array($v); })
->thenInvalid('Configuration value must be either string or array.')
->end()
->end()
->end();
Run Code Online (Sandbox Code Playgroud)
但是我如何source在变量节点的结构(操作,命令等)上添加约束(只应在其值为类型时强制执行array)?
Ben*_*cki 20
我认为您可以通过重构扩展来使用配置规范化.
在您的扩展中更改您的代码以检查是否设置了路径
if ($config['path'] !== null) {
// Bootstrap from file.
} else {
// Bootstrap from array.
}
Run Code Online (Sandbox Code Playgroud)
并允许用户使用字符串进行配置.
$rootNode
->children()
->arrayNode('source')
->beforeNormalization()
->ifString()
->then(function($value) { return array('path' => $value); })
->end()
->children()
->scalarNode('foo')
// ...
->end()
->end()
->end()
;
Run Code Online (Sandbox Code Playgroud)
像这样,您可以允许用户使用可以验证的字符串或数组.
希望它有用.最良好的问候.
可以将变量节点类型与一些自定义验证逻辑结合使用:
<?php
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\Exception\InvalidTypeException;
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('my_bundle');
$rootNode
->children()
->variableNode('source')
->validate()
->ifTrue(function ($v) {
return false === is_string($v) && false === is_array($v);
})
->thenInvalid('Here you message about why it is invalid')
->end()
->end()
->end();
;
return $treeBuilder;
}
Run Code Online (Sandbox Code Playgroud)
这将成功地过程:
my_bundle:
source: foo
# and
my_bundle:
source: [foo, bar]
Run Code Online (Sandbox Code Playgroud)
但它不会处理:
my_bundle:
source: 1
# or
my_bundle
source: ~
Run Code Online (Sandbox Code Playgroud)
当然,您将无法获得正常配置节点将为您提供的良好验证规则,并且您将无法在传递的数组(或字符串)上使用这些验证规则,但您将能够验证传递的数据使用的封闭.