在Symfony 2.1语义配置中允许数组(具有默认值)或null

Tho*_*zat 12 arrays symfony symfony-2.1

我需要在bundle的语义配置中定义一个具有给定默认值的数组节点.目前看起来像:

$node->arrayNode('foo')
         ->prototype('scalar')->end()
         ->defaultValue(array('1', '2', '3'))
     ->end();
Run Code Online (Sandbox Code Playgroud)

我想给用户提供覆盖此数组的选项,null如:

my_bundle:
  foo: ~
Run Code Online (Sandbox Code Playgroud)

我不能使用空数组([]array())而不是null给定[]应该具有不同语义的数组null.

这是可能的还是有任何非丑陋的解决方法?目前我只是得到一个例外:

InvalidTypeException:路径"my_bundle.foo"的类型无效.预期的数组,但得到NULL

Ald*_*nio 18

你可以尝试类似的东西:

$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();
Run Code Online (Sandbox Code Playgroud)

或者更简单:

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

否则你可以使用variableNode而不是arrayNode; 这将为您提供更多自由,但开箱即用的验证/合并逻辑更少.