Skip to content

Commit

Permalink
[HttpFoundation] added logic to automatically add the charset when no…
Browse files Browse the repository at this point in the history
…t present in the Content-Type for relevant Content-Types
  • Loading branch information
fabpot committed Apr 22, 2011
1 parent 150e248 commit fd05f02
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/Symfony/Component/HttpFoundation/Response.php
Expand Up @@ -86,6 +86,7 @@ public function __construct($content = '', $status = 200, $headers = array())
$this->setStatusCode($status);
$this->setProtocolVersion('1.0');
$this->headers = new ResponseHeaderBag($headers);
$this->charset = 'UTF-8';
}

/**
Expand All @@ -97,9 +98,7 @@ public function __toString()
{
$content = '';

if (!$this->headers->has('Content-Type')) {
$this->headers->set('Content-Type', 'text/html; charset='.(null === $this->charset ? 'UTF-8' : $this->charset));
}
$this->fixContentType();

// status
$content .= sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\n";
Expand Down Expand Up @@ -129,9 +128,7 @@ public function __clone()
*/
public function sendHeaders()
{
if (!$this->headers->has('Content-Type')) {
$this->headers->set('Content-Type', 'text/html; charset='.(null === $this->charset ? 'UTF-8' : $this->charset));
}
$this->fixContentType();

// status
header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText));
Expand Down Expand Up @@ -750,4 +747,14 @@ public function isRedirected($location)
{
return $this->isRedirect() && $location == $this->headers->get('Location');
}

protected function fixContentType()
{
if (!$this->headers->has('Content-Type')) {
$this->headers->set('Content-Type', 'text/html; charset='.$this->charset);
} elseif ('text/' === substr($this->headers->get('Content-Type'), 0, 5) && false === strpos($this->headers->get('Content-Type'), 'charset')) {
// add the charset
$this->headers->set('Content-Type', $this->headers->get('Content-Type').'; charset='.$this->charset);
}
}
}
11 changes: 11 additions & 0 deletions tests/Symfony/Tests/Component/HttpFoundation/ResponseTest.php
Expand Up @@ -188,6 +188,17 @@ public function testDefaultContentType()
$response->__toString();
}

public function testContentTypeCharset()
{
$response = new Response();
$response->headers->set('Content-Type', 'text/css');

// force fixContentType() to be called
$response->__toString();

$this->assertEquals('text/css; charset=UTF-8', $response->headers->get('Content-Type'));
}

public function testSetCache()
{
$response = new Response();
Expand Down

0 comments on commit fd05f02

Please sign in to comment.