很抱歉,我找不到将默认值添加到“symfony/config”:“2.6.4”配置接口的方法!
需要的是这种类型的配置:
X:
Y:
- test
- testing
默认为:
X:
Y:
- test
默认情况下,我的意思是:如果在读取配置文件上没有设置y config branch,那么$processor->processconfiguration应该添加它(它确实添加了!如果我删除->原型…)
这是我的代码:
class Definition implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root("X");
$rootNode
->children()
->arrayNode("Y")
->addDefaultsIfNotSet()
->info("Multiple values can be used")
->cannotBeEmpty()
->addDefaultIfNotSet()
->defaultValue(array("test"))
->prototype("scalar")
->validate()
->ifNotInArray(array("test", "testing"))
->thenInvalid("Invalid value %s")
->end()
->end()
->end()
->end()
;
return $treeBuilder;
}
}
当然,我读过这个问题Using the Symfony2 configuration class, how do I define an array node whose children don't have keys?
我当前的代码以这种方式实现,您可以阅读,但它不起作用,我的代码抛出:
[Symfony\Component\Config\Definition\Exception\InvalidDefinitionException]
->addDefaultsIfNotSet() is not applicable to prototype nodes at path "X.Y"
最佳答案
作为参考,我终于通过variablenode得到了它,就在我的头撞到墙上的前一分钟;)
class Definition implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root("X");
$rootNode
->children()
->variableNode("Y")
->info("Multiple values can be used")
->cannotBeEmpty()
->defaultValue(array("test"))
->validate()
->always(function ($values) {
foreach ((array) $values as $value) {
if (! in_array($value, array("test", "testing"))) {
throw new \Symfony\Component\Config\Definition\Exception\InvalidTypeException("Invalid value ".$value);
}
}
return (array) $values;
})
->end()
->end()
->end()
;
return $treeBuilder;
}
}
似乎没有办法用arraynode来实现这一点!但如果有人发现如何,请毫不犹豫地回答,我很乐意接受使用arraynode的答案,因为集成验证可能比我的好……
关于php - symfony/config arrayNode prototype addDefaultsIfNotSet,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29027116/