Can my configuration node source
support both string
and array
values?
Sourcing from string
:
# Valid configuration 1
my_bundle:
source: %kernel.root_dir%/../Resources/config/source.json
Sourcing from array
:
# Valid configuration 2
my_bundle:
source:
operations: []
commands: []
The extension class would be able to distinguish between them:
if (is_array($config['source']) {
// Bootstrap from array
} else {
// Bootstrap from file
}
I might use something like this:
$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();
But how ca I add constraints on the structure of source
(operations, commands, etc...) to the variable node (that should only be enforced when its value is of type array
)?
I think you can use the config normalization by refactoring your extension.
In your extension change your code to check if a path is set
if ($config['path'] !== null) {
// Bootstrap from file.
} else {
// Bootstrap from array.
}
And allow the user to use a string for config.
$rootNode
->children()
->arrayNode('source')
->beforeNormalization()
->ifString()
->then(function($value) { return array('path' => $value); })
->end()
->children()
->scalarNode('foo')
// ...
->end()
->end()
->end()
;
Like this you can allow the user to use a string or an array which can be validate.
See the symfony documentation for normalisation
Hope it's helpful. Best regard.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With