Browse Source

Use the immutable pattern for setEnv() which is now withEnv()

Michael Hoffmann 9 years ago
parent
commit
307dca88ac
2 changed files with 23 additions and 12 deletions
  1. 7 6
      src/Http/ServerRequest.php
  2. 16 6
      tests/TestCase/Http/ServerRequestTest.php

+ 7 - 6
src/Http/ServerRequest.php

@@ -1766,21 +1766,22 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
      *
      * @param string $key The key you want to write to.
      * @param string $value Value to set
-     * @return $this
+     * @return static
      */
-    public function setEnv($key, $value)
+    public function withEnv($key, $value)
     {
-        $this->_environment[$key] = $value;
-        $this->clearDetectorCache();
+        $new = clone $this;
+        $new->_environment[$key] = $value;
+        $new->clearDetectorCache();
 
-        return $this;
+        return $new;
     }
 
     /**
      * Get/Set value from the request's environment data.
      * Fallback to using env() if key not set in $environment property.
      *
-     * @deprecated 3.5.0 Use getEnv()/setEnv() instead.
+     * @deprecated 3.5.0 Use getEnv()/withEnv() instead.
      * @param string $key The key you want to read/write from/to.
      * @param string|null $value Value to set. Default null.
      * @param string|null $default Default value when trying to retrieve an environment

+ 16 - 6
tests/TestCase/Http/ServerRequestTest.php

@@ -3520,20 +3520,30 @@ XML;
     }
 
     /**
-     * Test setEnv() and getEnv()
+     * Test withEnv()
      *
      * @return void
      */
-    public function testGetSetEnv()
+    public function testWithEnv()
     {
         $request = new ServerRequest();
 
-        $request->setEnv('HTTP_HOST', 'cakephp.org');
-        $this->assertSame($request->getEnv('HTTP_HOST'), 'cakephp.org');
+        $newRequest = $request->withEnv('HTTP_HOST', 'cakephp.org');
+        $this->assertNotSame($request, $newRequest);
+        $this->assertSame($newRequest->getEnv('HTTP_HOST'), 'cakephp.org');
+    }
+
+    /**
+     * Test getEnv()
+     *
+     * @return void
+     */
+    public function testGetEnv()
+    {
+        $request = new ServerRequest();
 
         //Test default null
-        $request->setEnv('HTTP_HOST');
-        $this->assertSame($request->getEnv('HTTP_HOST'), null);
+        $this->assertSame($request->getEnv('Foo'), null);
 
         //Test default set
         $this->assertSame($request->getEnv('Foo', 'Bar'), 'Bar');