Skip to content

Commit 5243b4b

Browse files
committed
Internally refactor JSON::encode and ::decode to use JSON_THROW_ON_ERROR
Still want to throw our own custom exception for BC, but might as well use the native flag to catch and rethrow JSONException rather than asserting against json_last_error_message manually.
1 parent a8fa39f commit 5243b4b

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

src/StringEncoding/JSON.php

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
namespace Ingenerator\PHPUtils\StringEncoding;
44

55
use Ingenerator\PHPUtils\StringEncoding\InvalidJSONException;
6-
use function json_last_error_msg;
6+
use JsonException;
77

88
class JSON
99
{
@@ -16,13 +16,11 @@ public static function decode(?string $json)
1616
throw new InvalidJSONException('Invalid JSON: Cannot decode a null value');
1717
}
1818

19-
$result = json_decode($json, TRUE);
20-
21-
if (json_last_error() !== JSON_ERROR_NONE) {
22-
throw new InvalidJSONException('Invalid JSON: '.json_last_error_msg());
19+
try {
20+
return json_decode($json, associative: true, flags: JSON_THROW_ON_ERROR);
21+
} catch (JsonException $e) {
22+
throw new InvalidJSONException('Invalid JSON: '.$e->getMessage());
2323
}
24-
25-
return $result;
2624
}
2725

2826
public static function decodeArray(string $json): array
@@ -40,7 +38,6 @@ public static function decodeArray(string $json): array
4038
* @param bool $escaped_slashes defaults true to match the PHP default
4139
*
4240
* @return string
43-
* @throws \Ingenerator\PHPUtils\StringEncoding\InvalidJSONException
4441
*/
4542
public static function encode(
4643
$value,
@@ -51,13 +48,15 @@ public static function encode(
5148
($pretty ? JSON_PRETTY_PRINT : 0)
5249
|
5350
($escaped_slashes ? 0 : JSON_UNESCAPED_SLASHES)
51+
|
52+
JSON_THROW_ON_ERROR
5453
);
5554

56-
$json = json_encode($value, $flags);
57-
if (json_last_error() !== JSON_ERROR_NONE) {
58-
throw new \Ingenerator\PHPUtils\StringEncoding\InvalidJSONException('Could not encode as JSON : ' . json_last_error_msg());
55+
try {
56+
return json_encode($value, $flags);
57+
} catch (JsonException $e) {
58+
throw new InvalidJSONException('Could not encode as JSON: '.$e->getMessage());
5959
}
60-
return $json;
6160
}
6261

6362
/**

0 commit comments

Comments
 (0)