gpt4 book ai didi

symfony - 使配置节点在 Symfony 2 配置中同时支持字符串和数组?

转载 作者:行者123 更新时间:2023-12-03 20:04:52 25 4
gpt4 key购买 nike

可以我的配置节点source两者都支持stringarray值(value)观?

采购自 string :

# Valid configuration 1
my_bundle:
source: %kernel.root_dir%/../Resources/config/source.json

采购自 array :

# Valid configuration 2
my_bundle:
source:
operations: []
commands: []

扩展类将能够区分它们:

if (is_array($config['source']) {
// Bootstrap from array
} else {
// Bootstrap from file
}

我可能会使用这样的东西:

$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();

但是我如何在 source 的结构上添加约束(操作、命令等...)到变量节点(只有在其值类型为 array 时才应该强制执行)?

最佳答案

我认为您可以通过重构扩展来使用配置规范化。

在您的扩展程序中更改您的代码以检查是否设置了路径

if ($config['path'] !== null) {
// Bootstrap from file.
} else {
// Bootstrap from array.
}

并允许用户使用字符串进行配置。
$rootNode
->children()
->arrayNode('source')
->beforeNormalization()
->ifString()
->then(function($value) { return array('path' => $value); })
->end()
->children()
->scalarNode('foo')
// ...
->end()
->end()
->end()
;

像这样,您可以允许用户使用可以验证的字符串或数组。

symfony documentation for normalisation

希望它有帮助。
最良好的问候。

关于symfony - 使配置节点在 Symfony 2 配置中同时支持字符串和数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15922243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com