Browse Source

Implement withAddedHeader

Mark Story 9 years ago
parent
commit
dcedc0ce6d
2 changed files with 38 additions and 0 deletions
  1. 10 0
      src/Network/Request.php
  2. 28 0
      tests/TestCase/Network/RequestTest.php

+ 10 - 0
src/Network/Request.php

@@ -1046,6 +1046,16 @@ class Request implements ArrayAccess
      */
     public function withAddedHeader($name, $value)
     {
+        $new = clone $this;
+        $name = $this->normalizeHeaderName($name);
+        $existing = [];
+        if (isset($new->_environment[$name])) {
+            $existing = (array)$new->_environment[$name];
+        }
+        $existing = array_merge($existing, (array)$value);
+        $new->_environment[$name] = $existing;
+
+        return $new;
     }
 
     /**

+ 28 - 0
tests/TestCase/Network/RequestTest.php

@@ -1355,6 +1355,34 @@ class RequestTest extends TestCase
     }
 
     /**
+     * Test adding a header.
+     *
+     * @return void
+     */
+    public function testWithAddedHeader()
+    {
+        $request = new Request(['environment' => [
+            'HTTP_HOST' => 'localhost',
+            'CONTENT_TYPE' => 'application/json',
+            'CONTENT_LENGTH' => 1337,
+            'HTTP_CONTENT_MD5' => 'abc123',
+            'HTTP_DOUBLE' => ['a', 'b']
+        ]]);
+        $new = $request->withAddedHeader('Double', 'c');
+        $this->assertNotSame($new, $request);
+
+        $this->assertEquals('a, b', $request->getHeaderLine('Double'), 'old request is unchanged');
+        $this->assertEquals('a, b, c', $new->getHeaderLine('Double'), 'new request is correct');
+        $this->assertEquals(['a', 'b', 'c'], $new->header('Double'));
+
+        $new = $request->withAddedHeader('Content-Length', 777);
+        $this->assertEquals([1337, 777], $new->getHeader('Content-Length'), 'scalar values are appended');
+
+        $new = $request->withAddedHeader('Content-Length', [123, 456]);
+        $this->assertEquals([1337, 123, 456], $new->getHeader('Content-Length'), 'List values are merged');
+    }
+
+    /**
      * Test removing a header.
      *
      * @return void