浏览代码

[DependencyInjection] allow null for scalar nodes

Johannes M. Schmitt 14 年之前
父节点
当前提交
2b256a0804

+ 8 - 1
src/Symfony/Component/DependencyInjection/Configuration/ScalarNode.php

@@ -8,6 +8,13 @@ use Symfony\Component\DependencyInjection\Configuration\Exception\InvalidTypeExc
 /**
 /**
  * This node represents a scalar value in the config tree.
  * This node represents a scalar value in the config tree.
  *
  *
+ * The following values are considered scalars:
+ *   * booleans
+ *   * strings
+ *   * null
+ *   * integers
+ *   * floats
+ *
  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  */
  */
 class ScalarNode extends BaseNode implements PrototypeNodeInterface
 class ScalarNode extends BaseNode implements PrototypeNodeInterface
@@ -44,7 +51,7 @@ class ScalarNode extends BaseNode implements PrototypeNodeInterface
 
 
     protected function validateType($value)
     protected function validateType($value)
     {
     {
-        if (!is_scalar($value)) {
+        if (!is_scalar($value) && null !== $value) {
             throw new InvalidTypeException(sprintf(
             throw new InvalidTypeException(sprintf(
                 'Invalid type for path "%s". Expected scalar, but got %s.',
                 'Invalid type for path "%s". Expected scalar, but got %s.',
                 $this->getPath(),
                 $this->getPath(),

+ 49 - 0
tests/Symfony/Tests/Component/DependencyInjection/Configuration/ScalarNodeTest.php

@@ -0,0 +1,49 @@
+<?php
+
+namespace Symfony\Component\DependencyInjection\Configuration;
+
+class ScalarNodeTest extends \PHPUnit_Framework_TestCase
+{
+    /**
+     * @dataProvider getValidValues
+     */
+    public function testNormalize($value)
+    {
+        $node = new ScalarNode('test');
+        $this->assertSame($value, $node->normalize($value));
+    }
+
+    public function getValidValues()
+    {
+        return array(
+            array(false),
+            array(true),
+            array(null),
+            array(''),
+            array('foo'),
+            array(0),
+            array(1),
+            array(0.0),
+            array(0.1),
+        );
+    }
+
+    /**
+     * @dataProvider getInvalidValues
+     * @expectedException Symfony\Component\DependencyInjection\Configuration\Exception\InvalidTypeException
+     */
+    public function testNormalizeThrowsExceptionOnInvalidValues($value)
+    {
+        $node = new ScalarNode('test');
+        $node->normalize($value);
+    }
+
+    public function getInvalidValues()
+    {
+        return array(
+            array(array()),
+            array(array('foo' => 'bar')),
+            array(new \stdClass()),
+        );
+    }
+}