Added support for injecting HttpFoundation's RequestStack in ServerParams

This commit is contained in:
Charles Sarrazin 2014-05-16 14:30:08 +02:00
parent be1b917d21
commit 86f9cb90eb
2 changed files with 38 additions and 0 deletions

View File

@ -11,11 +11,20 @@
namespace Symfony\Component\Form\Extension\Validator\Util;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class ServerParams
{
private $requestStack;
public function __construct(RequestStack $requestStack = null)
{
$this->requestStack = $requestStack;
}
/**
* Returns maximum post size in bytes.
*
@ -65,6 +74,10 @@ class ServerParams
*/
public function getContentLength()
{
if (null !== $this->requestStack && null !== $request = $this->requestStack->getCurrentRequest()) {
return $request->server->get('CONTENT_LENGTH');
}
return isset($_SERVER['CONTENT_LENGTH'])
? (int) $_SERVER['CONTENT_LENGTH']
: null;

View File

@ -11,8 +11,33 @@
namespace Symfony\Component\Form\Tests\Extension\Validator\Util;
use Symfony\Component\Form\Extension\Validator\Util\ServerParams;
use Symfony\Component\HttpFoundation\Request;
class ServerParamsTest extends \PHPUnit_Framework_TestCase
{
public function testGetContentLengthFromSuperglobals()
{
$serverParams = new ServerParams();
$this->assertNull($serverParams->getContentLength());
$_SERVER['CONTENT_LENGTH'] = 1024;
$this->assertEquals(1024, $serverParams->getContentLength());
unset($_SERVER['CONTENT_LENGTH']);
}
public function testGetContentLengthFromRequest()
{
$request = Request::create('http://foo', 'GET', array(), array(), array(), array('CONTENT_LENGTH' => 1024));
$requestStack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack', array('getCurrentRequest'));
$requestStack->expects($this->once())->method('getCurrentRequest')->will($this->returnValue($request));
$serverParams = new ServerParams($requestStack);
$this->assertEquals(1024, $serverParams->getContentLength());
}
/** @dataProvider getGetPostMaxSizeTestData */
public function testGetPostMaxSize($size, $bytes)
{