소스 검색

[HttpFoundation] Added a way to grab the request body as a resource

Jordi Boggiano 14 년 전
부모
커밋
583340db7b
2개의 변경된 파일51개의 추가작업 그리고 3개의 파일을 삭제
  1. 15 3
      src/Symfony/Component/HttpFoundation/Request.php
  2. 36 0
      tests/Symfony/Tests/Component/HttpFoundation/RequestTest.php

+ 15 - 3
src/Symfony/Component/HttpFoundation/Request.php

@@ -617,12 +617,24 @@ class Request
     }
 
     /**
-     * Return the request body content.
+     * Returns the request body content.
      *
-     * @return string The request body content.
+     * @param  bool $asResource If true, a resource will be returned
+     *
+     * @return string|resource The request body content or a resource to read the body stream.
      */
-    public function getContent()
+    public function getContent($asResource = false)
     {
+        if (false === $this->content || (true === $asResource && null !== $this->content)) {
+            throw new \LogicException('getContent() can only be called once when using the resource return type.');
+        }
+
+        if (true === $asResource) {
+            $this->content = false;
+
+            return fopen('php://input', 'rb');
+        }
+
         if (null === $this->content) {
             $this->content = file_get_contents('php://input');
         }

+ 36 - 0
tests/Symfony/Tests/Component/HttpFoundation/RequestTest.php

@@ -478,6 +478,42 @@ class RequestTest extends \PHPUnit_Framework_TestCase
         $this->assertEquals($file, $files['child']['sub']['file']);
     }
 
+    public function testGetContentWorksTwiceInDefaultMode()
+    {
+        $req = new Request;
+        $this->assertEquals('', $req->getContent());
+        $this->assertEquals('', $req->getContent());
+    }
+
+    public function testGetContentReturnsResource()
+    {
+        $req = new Request;
+        $retval = $req->getContent(true);
+        $this->assertType('resource', $retval);
+        $this->assertEquals("", fread($retval, 1));
+        $this->assertTrue(feof($retval));
+    }
+
+    /**
+     * @expectedException LogicException
+     * @dataProvider getContentCantBeCalledTwiceWithResourcesProvider
+     */
+    public function testGetContentCantBeCalledTwiceWithResources($first, $second)
+    {
+        $req = new Request;
+        $req->getContent($first);
+        $req->getContent($second);
+    }
+
+    public function getContentCantBeCalledTwiceWithResourcesProvider()
+    {
+        return array(
+            'Resource then fetch' => array(true, false),
+            'Resource then resource' => array(true, true),
+            'Fetch then resource' => array(false, true),
+        );
+    }
+
     protected function createTempFile()
     {
         return tempnam(sys_get_temp_dir(), 'FormTest');