Skip to content

Commit 720aaf5

Browse files
authored
feat: better validation of invalid JSON payloads
1 parent 3eadeb6 commit 720aaf5

File tree

1 file changed

+17
-3
lines changed

1 file changed

+17
-3
lines changed

src/Controllers/ApiController.php

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,27 @@ public function init()
4646
$contentType = (string) $this->request->getHeader('Content-Type');
4747

4848
if (strpos($contentType, 'application/json') !== false) {
49-
$input = json_decode(file_get_contents("php://input"), true);
49+
$jsonPayload = trim(file_get_contents("php://input"));
50+
$input = json_decode($jsonPayload, true);
5051

5152
if ($input) {
5253
$this->vars = array_merge($input, $this->request->getVars());
54+
} else if ($jsonPayload) {
55+
$error = json_last_error();
56+
57+
switch ($error) {
58+
case JSON_ERROR_NONE:
59+
$this->vars = $this->request->getVars();
60+
break;
61+
default:
62+
$this->failure([
63+
'error' => 'Invalid JSON',
64+
'code' => $error
65+
]);
66+
break;
67+
}
5368
} else {
54-
$this->vars = $this->request->getVars();
69+
$this->vars = $this->request->requestVars();
5570
}
5671
} else {
5772
$this->vars = $this->request->requestVars();
@@ -377,7 +392,6 @@ public function getVar($name)
377392
public function hasVar($name)
378393
{
379394
$key = strtolower($name);
380-
381395
return (isset($this->vars[$key]));
382396
}
383397

0 commit comments

Comments
 (0)