Skip to content

Commit

Permalink
Fix Utils::json*() for native \JSON_THROW_ON_ERROR option (#3184)
Browse files Browse the repository at this point in the history
If a user passes the native `\JSON_THROW_ON_ERROR` option, these functions
would throw a `\JsonException` instead of the expected
`\InvalidArgumentException`.
  • Loading branch information
TimWolla committed Mar 31, 2024
1 parent 2fe9fd4 commit db32c20
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
19 changes: 8 additions & 11 deletions src/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -272,12 +272,11 @@ public static function isHostInNoProxy(string $host, array $noProxyArray): bool
*/
public static function jsonDecode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
{
$data = \json_decode($json, $assoc, $depth, $options);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_decode error: '.\json_last_error_msg());
try {
return \json_decode($json, $assoc, $depth, $options | \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new InvalidArgumentException('json_decode error: '.$e->getMessage(), 0, $e);
}

return $data;
}

/**
Expand All @@ -293,13 +292,11 @@ public static function jsonDecode(string $json, bool $assoc = false, int $depth
*/
public static function jsonEncode($value, int $options = 0, int $depth = 512): string
{
$json = \json_encode($value, $options, $depth);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_encode error: '.\json_last_error_msg());
try {
return \json_encode($value, $options | \JSON_THROW_ON_ERROR, $depth);
} catch (\JsonException $e) {
throw new InvalidArgumentException('json_encode error: '.$e->getMessage(), 0, $e);
}

/** @var string */
return $json;
}

/**
Expand Down
14 changes: 14 additions & 0 deletions tests/UtilsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,13 @@ public function testEncodesJsonAndThrowsOnErrorLegacy()
\GuzzleHttp\json_encode("\x99");
}

public function testEncodesJsonAndThrowsOnErrorWithNativeOption()
{
$this->expectException(\InvalidArgumentException::class);

Utils::jsonEncode("\x99", \JSON_THROW_ON_ERROR);
}

public function testDecodesJson()
{
self::assertTrue(Utils::jsonDecode('true'));
Expand All @@ -187,6 +194,13 @@ public function testDecodesJsonAndThrowsOnErrorLegacy()

\GuzzleHttp\json_decode('{{]]');
}

public function testDecodesJsonAndThrowsOnErrorWithNativeOption()
{
$this->expectException(\InvalidArgumentException::class);

Utils::jsonDecode('{{]]', false, 512, \JSON_THROW_ON_ERROR);
}
}

final class StrClass
Expand Down

0 comments on commit db32c20

Please sign in to comment.