Browse Source

Add withCharset() immutable helper.

Mark Story 9 years ago
parent
commit
f22ec68869
2 changed files with 32 additions and 0 deletions
  1. 16 0
      src/Network/Response.php
  2. 16 0
      tests/TestCase/Network/ResponseTest.php

+ 16 - 0
src/Network/Response.php

@@ -1150,6 +1150,7 @@ class Response implements ResponseInterface
      *
      * @param string|null $charset Character set string.
      * @return string Current charset
+     * @deprecated 3.4.0 Use withCharset() instead.
      */
     public function charset($charset = null)
     {
@@ -1163,6 +1164,21 @@ class Response implements ResponseInterface
     }
 
     /**
+     * Get a new instance with an updated charset.
+     *
+     * @param string $charset Character set string.
+     * @return static
+     */
+    public function withCharset($charset)
+    {
+        $new = clone $this;
+        $new->_charset = $charset;
+        $new->_setContentType();
+
+        return $new;
+    }
+
+    /**
      * Sets the correct headers to instruct the client to not cache the response
      *
      * @return void

+ 16 - 0
tests/TestCase/Network/ResponseTest.php

@@ -131,6 +131,22 @@ class ResponseTest extends TestCase
     }
 
     /**
+     * Tests withCharset method
+     *
+     * @return void
+     */
+    public function testWithCharset()
+    {
+        $response = new Response();
+        $this->assertEquals('text/html; charset=UTF-8', $response->getHeaderLine('Content-Type'));
+
+        $new = $response->withCharset('iso-8859-1');
+        $this->assertNotContains('iso', $response->getHeaderLine('Content-Type'), 'Old instance not changed');
+
+        $this->assertEquals('text/html; charset=iso-8859-1', $new->getHeaderLine('Content-Type'));
+    }
+
+    /**
      * Tests the statusCode method
      *
      * @expectedException \InvalidArgumentException