Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: the json_last_error will not reset when using JSON_THROW_ON_ERROR flag #405

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/Exceptions/JsonException.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,9 @@ public static function createFromPhpError(): self
{
return new self(\json_last_error_msg(), \json_last_error());
}

public static function createFromJsonException(\JsonException $e): self
{
return new self($e->getMessage(), $e->getCode());
}
}
10 changes: 7 additions & 3 deletions lib/special_cases.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,13 @@
*/
function json_decode(string $json, bool $assoc = false, int $depth = 512, int $flags = 0): mixed
{
$data = \json_decode($json, $assoc, $depth, $flags);
if (JSON_ERROR_NONE !== json_last_error()) {
throw JsonException::createFromPhpError();
try {
$data = \json_decode($json, $assoc, $depth, $flags);
if (JSON_ERROR_NONE !== json_last_error() && !($flags && JSON_THROW_ON_ERROR)) {
throw JsonException::createFromPhpError();
}
} catch (\JsonException $e) {
throw JsonException::createFromJsonException($e);
}
return $data;
}
Expand Down
51 changes: 51 additions & 0 deletions tests/JsonDecodeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

declare(strict_types=1);

use PHPUnit\Framework\TestCase;

final class JsonDecodeTest extends TestCase
{
public function testJsonDecode()
{
// assert valid json
$this->assertSame(
[],
\Safe\json_decode("[]"),
);
}

public function testInvalidJsonDecode()
{
// create json error
\json_decode("\00 invalid json");
$this->assertGreaterThan(0, json_last_error());

$this->expectException(\Safe\Exceptions\JsonException::class);
\Safe\json_decode("\00 invalid json");

}

public function testJsonDecodeWithJsonThrowOnErrorFlag()
{
// create json error
\json_decode("\00 invalid json");
$this->assertGreaterThan(0, json_last_error());

// assert valid json
$this->assertSame(
[],
\Safe\json_decode("[]", true, 512, JSON_THROW_ON_ERROR),
);
}

public function testInvalidJsonDecodeWithJsonThrowOnErrorFlag()
{
// create json error
\json_decode("\00 invalid json");
$this->assertGreaterThan(0, json_last_error());

$this->expectException(\Safe\Exceptions\JsonException::class);
\Safe\json_decode("\00 invalid json", true, 512, JSON_THROW_ON_ERROR);
}
}