Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 223
gremo Avatar asked Apr 10 '13 09:04

gremo


1 Answers

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.

like image 197
Benjamin Lazarecki Avatar answered Oct 13 '22 23:10

Benjamin Lazarecki