3
3
namespace Ingenerator \PHPUtils \StringEncoding ;
4
4
5
5
use Ingenerator \PHPUtils \StringEncoding \InvalidJSONException ;
6
- use function json_last_error_msg ;
6
+ use JsonException ;
7
7
8
8
class JSON
9
9
{
@@ -16,13 +16,11 @@ public static function decode(?string $json)
16
16
throw new InvalidJSONException ('Invalid JSON: Cannot decode a null value ' );
17
17
}
18
18
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 ());
23
23
}
24
-
25
- return $ result ;
26
24
}
27
25
28
26
public static function decodeArray (string $ json ): array
@@ -34,13 +32,31 @@ public static function decodeArray(string $json): array
34
32
return $ value ?: [];
35
33
}
36
34
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 ());
42
59
}
43
- return $ json ;
44
60
}
45
61
46
62
/**
0 commit comments