Making configuration node support both string and array in Symfony 2 configuration? Making configuration node support both string and array in Symfony 2 configuration? symfony symfony

Making configuration node support both string and array in Symfony 2 configuration?


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.


It is possible to use a variable node type in combination with some custom validation logic:

<?phpuse 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;}

This will succesfully process:

my_bundle:    source: foo# andmy_bundle:    source: [foo, bar]

but it won't process:

my_bundle:    source: 1# ormy_bundle    source: ~

Of course, you won't get the nice validation rules a normal configuration node will provide you and you won't be able to use those validation rules on the array (or string) passed but you will be able to validate the passed data in the closure used.