Browse Source

Throw exception if `post` key is not a valid type

Corey Taylor 4 years ago
parent
commit
044b722efd
2 changed files with 16 additions and 7 deletions
  1. 11 3
      src/Http/ServerRequest.php
  2. 5 4
      tests/TestCase/Http/ServerRequestTest.php

+ 11 - 3
src/Http/ServerRequest.php

@@ -55,9 +55,9 @@ class ServerRequest implements ServerRequestInterface
      * In PUT/PATCH/DELETE requests this property will contain the form-urlencoded
      * data.
      *
-     * @var object|array|string|null
+     * @var object|array|null
      */
-    protected object|array|string|null $data = [];
+    protected object|array|null $data = [];
 
     /**
      * Array of query string arguments
@@ -290,7 +290,15 @@ class ServerRequest implements ServerRequestInterface
         }
         $this->stream = $stream;
 
-        $this->data = $config['post'];
+        $post = $config['post'];
+        if (!(is_array($post) || is_object($post) || $post === null)) {
+            throw new InvalidArgumentException(sprintf(
+                '`post` key must be an array, object or null.'
+                . ' Got `%s` instead.',
+                get_debug_type($post)
+            ));
+        }
+        $this->data = $post;
         $this->uploadedFiles = $config['files'];
         $this->query = $config['query'];
         $this->params = $config['params'];

+ 5 - 4
tests/TestCase/Http/ServerRequestTest.php

@@ -1220,14 +1220,15 @@ class ServerRequestTest extends TestCase
     }
 
     /**
-     * Test that getData() doesn't fail on scalar data.
+     * Test setting post data to a string throws exception.
      */
-    public function testGetDataOnStringData(): void
+    public function testInvalidStringData(): void
     {
+        $this->expectException(InvalidArgumentException::class);
+        $this->expectExceptionMessage('`post` key must be an array, object or null. Got `string` instead.');
+
         $post = 'strange, but could happen';
         $request = new ServerRequest(compact('post'));
-        $this->assertNull($request->getData('Model'));
-        $this->assertNull($request->getData('Model.field'));
     }
 
     /**