浏览代码

Implement withHeader()

Mark Story 9 年之前
父节点
当前提交
cea85d7b4f
共有 2 个文件被更改,包括 32 次插入0 次删除
  1. 8 0
      src/Network/Request.php
  2. 24 0
      tests/TestCase/Network/RequestTest.php

+ 8 - 0
src/Network/Request.php

@@ -1019,6 +1019,14 @@ class Request implements ArrayAccess
      */
     public function withHeader($name, $value)
     {
+        $new = clone $this;
+        $name = strtoupper(str_replace('-', '_', $name));
+        if (!in_array($name, ['CONTENT_LENGTH', 'CONTENT_TYPE'])) {
+            $name = 'HTTP_' . $name;
+        }
+        $new->_environment[$name] = $value;
+
+        return $new;
     }
 
     /**

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

@@ -1329,6 +1329,30 @@ class RequestTest extends TestCase
     }
 
     /**
+     * Test setting a header.
+     *
+     * @return void
+     */
+    public function testWithHeader()
+    {
+        $request = new Request(['environment' => [
+            'HTTP_HOST' => 'localhost',
+            'CONTENT_TYPE' => 'application/json',
+            'CONTENT_LENGTH' => 1337,
+            'HTTP_CONTENT_MD5' => 'abc123',
+            'HTTP_DOUBLE' => ['a', 'b']
+        ]]);
+        $new = $request->withHeader('Content-Length', 999);
+        $this->assertNotSame($new, $request);
+
+        $this->assertEquals(1337, $request->getHeaderLine('Content-length'), 'old request is unchanged');
+        $this->assertEquals(999, $new->getHeaderLine('Content-length'), 'new request is correct');
+
+        $new = $request->withHeader('Double', ['a']);
+        $this->assertEquals(['a'], $new->getHeader('Double'), 'List values are overwritten');
+    }
+
+    /**
      * Test accepts() with and without parameters
      *
      * @return void