Browse Source

Add ServerRequest::withoutData()

In order to update CsrfComponent we need a new method to remove data
from the request in an immutable pattern.
mark_story 8 years ago
parent
commit
a48e9483ee
2 changed files with 39 additions and 0 deletions
  1. 17 0
      src/Http/ServerRequest.php
  2. 22 0
      tests/TestCase/Http/ServerRequestTest.php

+ 17 - 0
src/Http/ServerRequest.php

@@ -1968,6 +1968,23 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
     }
 
     /**
+     * Update the request removing a data element.
+     *
+     * Returns an updated request object. This method returns
+     * a *new* request object and does not mutate the request in-place.
+     *
+     * @param string $name The dot separated path to remove.
+     * @return static
+     */
+    public function withoutData($name)
+    {
+        $copy = clone $this;
+        $copy->data = Hash::remove($copy->data, $name);
+
+        return $copy;
+    }
+
+    /**
      * Update the request with a new routing parameter
      *
      * Returns an updated request object. This method returns

+ 22 - 0
tests/TestCase/Http/ServerRequestTest.php

@@ -3392,6 +3392,28 @@ XML;
     }
 
     /**
+     * Test removing data from a request
+     *
+     * @return void
+     */
+    public function testWithoutData()
+    {
+        $request = new ServerRequest([
+            'post' => [
+                'Model' => [
+                    'id' => 1,
+                    'field' => 'value'
+                ]
+            ]
+        ]);
+        $updated = $request->withoutData('Model.field');
+        $this->assertNotSame($updated, $request);
+        $this->assertSame('value', $request->getData('Model.field'), 'Original request should not change.');
+        $this->assertNull($updated->getData('Model.field'), 'data removed from updated request');
+        $this->assertFalse(isset($updated->getData()['Model']['field']), 'data removed from updated request');
+    }
+
+    /**
      * Test updating POST data when keys don't exist
      *
      * @return void