Przeglądaj źródła

Merge pull request #333 from saraf/master

Correct 400 response to malformed json in POST
Maurits van der Schee 6 lat temu
rodzic
commit
0b8eeee07a
No account linked to committer's email address
3 zmienionych plików z 33 dodań i 1 usunięć
  1. 14
    0
      api.php
  2. 18
    0
      tests/Api.php
  3. 1
    1
      tests/Tests.php

+ 14
- 0
api.php Wyświetl plik

@@ -1270,6 +1270,15 @@ class PHP_CRUD_API {
1270 1270
 		}
1271 1271
 	}
1272 1272
 
1273
+	protected function exitWith400($type) {
1274
+		if (isset($_SERVER['REQUEST_METHOD'])) {
1275
+			header('Content-Type:',true,400);
1276
+			die("The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications. ($type)");
1277
+		} else {
1278
+			throw new \Exception("Bad request ($type)");
1279
+		}
1280
+	}
1281
+
1273 1282
 	protected function exitWith422($object) {
1274 1283
 		if (isset($_SERVER['REQUEST_METHOD'])) {
1275 1284
 			header('Content-Type:',true,422);
@@ -1684,6 +1693,11 @@ class PHP_CRUD_API {
1684 1693
 			$input = false;
1685 1694
 		} else if ($data[0]=='{' || $data[0]=='[') {
1686 1695
 			$input = json_decode($data);
1696
+			$causeCode = json_last_error();
1697
+			if ($causeCode !== JSON_ERROR_NONE) {
1698
+				$errorString = "Error decoding input JSON. json_last_error code: " . $causeCode;
1699
+				$this->exitWith400($errorString);
1700
+			}
1687 1701
 		} else {
1688 1702
 			parse_str($data, $input);
1689 1703
 			foreach ($input as $key => $value) {

+ 18
- 0
tests/Api.php Wyświetl plik

@@ -138,4 +138,22 @@ class Api
138 138
         }
139 139
         return $this;
140 140
     }
141
+
142
+    public function expectPattern($expectedOutputPattern, $expectedErrorPattern) {
143
+        $exception = false;
144
+        ob_start();
145
+        try {
146
+            $this->api->executeCommand();
147
+        } catch (\Exception $e) {
148
+            $exception = $e->getMessage();
149
+        }
150
+        $outputData = ob_get_contents();
151
+        ob_end_clean();
152
+        if ($exception) {
153
+            $this->test->assertRegExp($expectedErrorPattern, $exception);
154
+        } else {
155
+            $this->test->assertRegExp($expectedOutputPattern, $outputData);
156
+        }
157
+        return $this;
158
+    }
141 159
 }

+ 1
- 1
tests/Tests.php Wyświetl plik

@@ -290,7 +290,7 @@ abstract class Tests extends TestBase
290 290
     {
291 291
         $test = new Api($this);
292 292
         $test->post('/posts', '{"}');
293
-        $test->expect(false, 'Not found (input)');
293
+        $test->expectPattern(false, '/^Bad request.*$/');
294 294
     }
295 295
 
296 296
     public function testErrorOnDuplicatePrimaryKey()

Loading…
Anuluj
Zapisz