Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow array (with default value) or null in Symfony 2.1 semantic configuration

I need to define an array node with a given default value in a bundle's semantic configuration. This currently looks like:

$node->arrayNode('foo')
         ->prototype('scalar')->end()
         ->defaultValue(array('1', '2', '3'))
     ->end();

I want to give the user the option to override this array with null like:

my_bundle:
  foo: ~

I cannot use empty arrays ([] or array()) instead of null given that [] should have different semantics from null.

Is this possible or are there any non-ugly workarounds? Currently I just get an exception:

InvalidTypeException: Invalid type for path "my_bundle.foo". Expected array, but got NULL

like image 733
Thomas Luzat Avatar asked Oct 31 '12 00:10

Thomas Luzat


1 Answers

You could try something like:

$node->arrayNode('foo')
     ->beforeNormalization()
       ->ifTrue(function($v) { return $v === null; })
       ->then(function($v) { return array(); })
     ->end()
     ->prototype('scalar')->end()
     ->defaultValue(array('1', '2', '3'))
 ->end();

Or maybe the even simplier:

$node->arrayNode('foo')
     ->treatNullLike(array())
     ->prototype('scalar')->end()
     ->defaultValue(array('1', '2', '3'))
 ->end();

Otherwise you can use the variableNode rather than the arrayNode; this will give you more freedom but less validation/merging logic out of the box.

like image 168
Aldo Stracquadanio Avatar answered Oct 20 '22 02:10

Aldo Stracquadanio