ソースを参照

[HttpFoundation] Allow stringable objects and numbers in response body + added tests

Jordi Boggiano 14 年 前
コミット
7af003b753

+ 5 - 3
src/Symfony/Component/HttpFoundation/Response.php

@@ -161,12 +161,14 @@ class Response
     /**
      * Sets the response content
      *
-     * @param string $content
+     * Valid types are strings, numbers, and objects that implement a __toString() method.
+     *
+     * @param mixed $content
      */
     public function setContent($content)
     {
-        if (!is_string($content)) {
-            throw new \UnexpectedValueException('The Response content must be a string, "'.gettype($content).'" given.');
+        if (!is_string($content) && !is_numeric($content) && !is_callable(array($content, '__toString'))) {
+            throw new \UnexpectedValueException('The Response content must be a string or object implementing __toString(), "'.gettype($content).'" given.');
         }
         $this->content = $content;
     }

+ 46 - 0
tests/Symfony/Tests/Component/HttpFoundation/ResponseTest.php

@@ -424,6 +424,44 @@ class ResponseTest extends \PHPUnit_Framework_TestCase
         $this->assertNull($response->headers->get('Etag'), '->setEtag() removes Etags when call with null');
     }
 
+    /**
+     * @dataProvider validContentProvider
+     */
+    public function testSetContent($content)
+    {
+        $response = new Response();
+        $response->setContent($content);
+        $this->assertEquals($content, $response->getContent());
+    }
+
+    /**
+     * @expectedException UnexpectedValueException
+     * @dataProvider invalidContentProvider
+     */
+    public function testSetContentInvalid($content)
+    {
+        $response = new Response();
+        $response->setContent($content);
+    }
+
+    public function validContentProvider()
+    {
+        return array(
+            'obj'    => array(new StringableObject),
+            'string' => array('Foo'),
+            'int'    => array(2),
+        );
+    }
+
+    public function invalidContentProvider()
+    {
+        return array(
+            'obj'   => array(new \stdClass),
+            'array' => array(array()),
+            'bool'   => array(true, '1'),
+        );
+    }
+
     protected function createDateTimeOneHourAgo()
     {
         $date = new \DateTime();
@@ -443,3 +481,11 @@ class ResponseTest extends \PHPUnit_Framework_TestCase
         return new \DateTime();
     }
 }
+
+class StringableObject
+{
+    public function __toString()
+    {
+        return 'Foo';
+    }
+}