33namespace Ingenerator \PHPUtils \StringEncoding ;
44
55use Ingenerator \PHPUtils \StringEncoding \InvalidJSONException ;
6- use function json_last_error_msg ;
6+ use JsonException ;
77
88class 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
@@ -34,13 +32,31 @@ public static function decodeArray(string $json): array
3432 return $ value ?: [];
3533 }
3634
37- public static function encode ($ value , bool $ pretty = TRUE ): string
38- {
39- $ json = json_encode ($ value , $ pretty ? JSON_PRETTY_PRINT : 0 );
40- if (json_last_error () !== JSON_ERROR_NONE ) {
41- throw new \Ingenerator \PHPUtils \StringEncoding \InvalidJSONException ('Could not encode as JSON : ' . json_last_error_msg ());
35+ /**
36+ * @param mixed $value
37+ * @param bool $pretty
38+ * @param bool $escaped_slashes defaults true to match the PHP default
39+ *
40+ * @return string
41+ */
42+ public static function encode (
43+ $ value ,
44+ bool $ pretty = true ,
45+ bool $ escaped_slashes = true ,
46+ ): string {
47+ $ flags = (
48+ ($ pretty ? JSON_PRETTY_PRINT : 0 )
49+ |
50+ ($ escaped_slashes ? 0 : JSON_UNESCAPED_SLASHES )
51+ |
52+ JSON_THROW_ON_ERROR
53+ );
54+
55+ try {
56+ return json_encode ($ value , $ flags );
57+ } catch (JsonException $ e ) {
58+ throw new InvalidJSONException ('Could not encode as JSON: ' .$ e ->getMessage ());
4259 }
43- return $ json ;
4460 }
4561
4662 /**
0 commit comments