fixed a bug in Response content-type auto-detection

Without this patch, if you call __toString() on a Response,
the content-type auto-detection would never be trigerred
as __toString() changes the default content-type.
This commit is contained in:
Fabien Potencier 2011-02-21 16:56:42 +01:00
parent f21578e819
commit bf20238178
4 changed files with 21 additions and 5 deletions

View File

@ -34,6 +34,7 @@
<service id="response_listener" class="%response_listener.class%">
<tag name="kernel.listener" event="core.response" method="filter" />
<argument>%kernel.charset%</argument>
</service>
<service id="exception_listener" class="%exception_listener.class%">

View File

@ -27,7 +27,7 @@ class Response
protected $version;
protected $statusCode;
protected $statusText;
protected $charset = 'UTF-8';
protected $charset;
static public $statusTexts = array(
100 => 'Continue',
@ -98,7 +98,7 @@ class Response
$content = '';
if (!$this->headers->has('Content-Type')) {
$this->headers->set('Content-Type', 'text/html; charset='.$this->charset);
$this->headers->set('Content-Type', 'text/html; charset='.(null === $this->charset ? 'UTF-8' : $this->charset));
}
// status
@ -130,7 +130,7 @@ class Response
public function sendHeaders()
{
if (!$this->headers->has('Content-Type')) {
$this->headers->set('Content-Type', 'text/html; charset='.$this->charset);
$this->headers->set('Content-Type', 'text/html; charset='.(null === $this->charset ? 'UTF-8' : $this->charset));
}
// status

View File

@ -23,6 +23,13 @@ use Symfony\Component\HttpFoundation\Response;
*/
class ResponseListener
{
protected $charset;
public function __construct($charset)
{
$this->charset = $charset;
}
/**
* Filters the Response.
*
@ -31,7 +38,15 @@ class ResponseListener
*/
public function filter(EventInterface $event, Response $response)
{
if (HttpKernelInterface::MASTER_REQUEST !== $event->get('request_type') || $response->headers->has('Content-Type')) {
if (HttpKernelInterface::MASTER_REQUEST !== $event->get('request_type')) {
return $response;
}
if (null === $response->getCharset()) {
$response->setCharset($this->charset);
}
if ($response->headers->has('Content-Type')) {
return $response;
}

View File

@ -59,7 +59,7 @@ class ResponseListenerTest extends \PHPUnit_Framework_TestCase
protected function getDispatcher()
{
$dispatcher = new EventDispatcher();
$listener = new ResponseListener();
$listener = new ResponseListener('UTF-8');
$dispatcher->connect('core.response', array($listener, 'filter'));
return $dispatcher;