Skip to content

Commit d7ad228

Browse files
authored
Merge pull request #5392 from kenjis/fix-getJsonVar
fix: `IncomingRequest::getJsonVar()` may cause TypeError
2 parents d4115dd + 9c9c4d2 commit d7ad228

2 files changed

Lines changed: 29 additions & 2 deletions

File tree

system/HTTP/IncomingRequest.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -520,7 +520,7 @@ public function getVar($index = null, $filter = null, $flags = null)
520520
*/
521521
public function getJSON(bool $assoc = false, int $depth = 512, int $options = 0)
522522
{
523-
return json_decode($this->body, $assoc, $depth, $options);
523+
return json_decode($this->body ?? '', $assoc, $depth, $options);
524524
}
525525

526526
/**
@@ -537,7 +537,11 @@ public function getJsonVar(string $index, bool $assoc = false, ?int $filter = nu
537537
{
538538
helper('array');
539539

540-
$data = dot_array_search($index, $this->getJSON(true));
540+
$json = $this->getJSON(true);
541+
if (! is_array($json)) {
542+
return null;
543+
}
544+
$data = dot_array_search($index, $json);
541545

542546
if ($data === null) {
543547
return null;

tests/system/HTTP/IncomingRequestTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,29 @@ public function testGetVarWorksWithJsonAndGetParams()
394394
$this->assertSame('buzz', $all['fizz']);
395395
}
396396

397+
/**
398+
* @see https://github.com/codeigniter4/CodeIgniter4/issues/5391
399+
*/
400+
public function testGetJsonVarReturnsNullFromNullBody()
401+
{
402+
$config = new App();
403+
$config->baseURL = 'http://example.com/';
404+
$json = null;
405+
$request = new IncomingRequest($config, new URI(), $json, new UserAgent());
406+
407+
$this->assertNull($request->getJsonVar('myKey'));
408+
}
409+
410+
public function testgetJSONReturnsNullFromNullBody()
411+
{
412+
$config = new App();
413+
$config->baseURL = 'http://example.com/';
414+
$json = null;
415+
$request = new IncomingRequest($config, new URI(), $json, new UserAgent());
416+
417+
$this->assertNull($request->getJSON());
418+
}
419+
397420
public function testCanGrabGetRawInput()
398421
{
399422
$rawstring = 'username=admin001&role=administrator&usepass=0';

0 commit comments

Comments
 (0)