Просмотр исходного кода

[HttpFoundation] added logic to automatically add the charset when not present in the Content-Type for relevant Content-Types

Fabien Potencier 14 лет назад
Родитель
Сommit
fd05f02b23

+ 13 - 6
src/Symfony/Component/HttpFoundation/Response.php

@@ -86,6 +86,7 @@ class Response
         $this->setStatusCode($status);
         $this->setProtocolVersion('1.0');
         $this->headers = new ResponseHeaderBag($headers);
+        $this->charset = 'UTF-8';
     }
 
     /**
@@ -97,9 +98,7 @@ class Response
     {
         $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";
@@ -129,9 +128,7 @@ class Response
      */
     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));
@@ -750,4 +747,14 @@ class Response
     {
         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 - 0
tests/Symfony/Tests/Component/HttpFoundation/ResponseTest.php

@@ -188,6 +188,17 @@ class ResponseTest extends \PHPUnit_Framework_TestCase
         $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();