13

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

2
  • You defined this as 'scalar' but default value is 'array', should it be array type? Scalar is integer, boolean, string Commented Oct 31, 2012 at 11:30
  • 1
    The prototype refers to the array's elements. Commented Oct 31, 2012 at 12:25

1 Answer 1

20

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but this looks as if I will get array() for null instead of null. I almost suspect that there is no other choice, though. It would probably be hard to express "override with null" vs. empty array in XML, too (not so much for Yaml).
Yes, that is what is going to happen, but I think that there is no easy escape from this: if you define an arrayNode you will eventually get an array after the configuration has been merged and normalized. You could consider having the foo node as a variableNode otherwise, which will give you more freedom but less validation/merging logic out of the box.
If you added the variableNode part to the answer, I could accept it, given that I explicitly asked for a way which allows to consider [] different from null. arrayNode does not seem to be an option which fully does what I want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.