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

This commit is contained in:
Jordi Boggiano 2010-12-13 00:22:47 +01:00 committed by Fabien Potencier
parent 9fef10f67d
commit 583340db7b
2 changed files with 51 additions and 3 deletions

View File

@ -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');
}

View File

@ -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');