Skip to content

Commit

Permalink
json_decode fixes
Browse files Browse the repository at this point in the history
(Breaking the diff against shish/safe into smaller parts for easier reviewing)
  • Loading branch information
shish committed Nov 28, 2024
1 parent 3a6e43b commit acffa2e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
8 changes: 4 additions & 4 deletions lib/special_cases.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
* Wrapper for json_decode that throws when an error occurs.
*
* @param string $json JSON data to parse
* @param bool $assoc When true, returned objects will be converted
* @param bool $associative When true, returned objects will be converted
* into associative arrays.
* @param int<1, max> $depth User specified recursion depth.
* @param int $flags Bitmask of JSON decode options.
Expand All @@ -33,10 +33,10 @@
* @throws JsonException if the JSON cannot be decoded.
* @link http://www.php.net/manual/en/function.json-decode.php
*/
function json_decode(string $json, bool $assoc = false, int $depth = 512, int $flags = 0): mixed
function json_decode(string $json, bool $associative = false, int $depth = 512, int $flags = 0): mixed
{
$data = \json_decode($json, $assoc, $depth, $flags);
if (JSON_ERROR_NONE !== json_last_error()) {
$data = \json_decode($json, $associative, $depth, $flags);
if (!($flags & JSON_THROW_ON_ERROR) && JSON_ERROR_NONE !== json_last_error()) {
throw JsonException::createFromPhpError();
}
return $data;
Expand Down
16 changes: 16 additions & 0 deletions tests/JsonDecodeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

use PHPUnit\Framework\TestCase;

final class JsonDecodeTest extends TestCase
{
public function testJsonLastErrorIsNotCheckedIfFlagIsSet(): void
{
\json_decode('{');
self::assertNotSame(JSON_ERROR_NONE, \json_last_error());

\Safe\json_decode('[]', flags: \JSON_THROW_ON_ERROR);
}
}

0 comments on commit acffa2e

Please sign in to comment.