1: | <?php declare(strict_types=1); |
2: | |
3: | namespace Salient\Utility; |
4: | |
5: | /** |
6: | * Wrappers for json_encode() and json_decode() that throw exceptions on failure |
7: | * |
8: | * @api |
9: | */ |
10: | final class Json extends AbstractUtility |
11: | { |
12: | /** |
13: | * Flags always passed to json_encode() |
14: | */ |
15: | public const ENCODE_FLAGS = \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE; |
16: | |
17: | /** |
18: | * Flags always passed to json_decode() |
19: | */ |
20: | public const DECODE_FLAGS = \JSON_THROW_ON_ERROR; |
21: | |
22: | /** |
23: | * Convert a value to a JSON string |
24: | * |
25: | * @param mixed $value |
26: | * @param int-mask-of<\JSON_FORCE_OBJECT|\JSON_INVALID_UTF8_IGNORE|\JSON_INVALID_UTF8_SUBSTITUTE|\JSON_NUMERIC_CHECK|\JSON_PRESERVE_ZERO_FRACTION|\JSON_PRETTY_PRINT|\JSON_THROW_ON_ERROR|\JSON_UNESCAPED_SLASHES|\JSON_UNESCAPED_UNICODE> $flags |
27: | */ |
28: | public static function stringify($value, int $flags = 0): string |
29: | { |
30: | return json_encode($value, self::ENCODE_FLAGS | $flags); |
31: | } |
32: | |
33: | /** |
34: | * Convert a value to a human-readable JSON string with native line endings |
35: | * |
36: | * @param mixed $value |
37: | * @param int-mask-of<\JSON_FORCE_OBJECT|\JSON_INVALID_UTF8_IGNORE|\JSON_INVALID_UTF8_SUBSTITUTE|\JSON_NUMERIC_CHECK|\JSON_PRESERVE_ZERO_FRACTION|\JSON_THROW_ON_ERROR|\JSON_UNESCAPED_SLASHES|\JSON_UNESCAPED_UNICODE> $flags |
38: | */ |
39: | public static function prettyPrint($value, int $flags = 0, string $eol = \PHP_EOL): string |
40: | { |
41: | $json = json_encode($value, self::ENCODE_FLAGS | \JSON_PRETTY_PRINT | $flags); |
42: | return $eol === "\n" |
43: | ? $json |
44: | : str_replace("\n", $eol, $json); |
45: | } |
46: | |
47: | /** |
48: | * Convert a JSON string to a value |
49: | * |
50: | * @param int-mask-of<\JSON_BIGINT_AS_STRING|\JSON_INVALID_UTF8_IGNORE|\JSON_INVALID_UTF8_SUBSTITUTE|\JSON_OBJECT_AS_ARRAY|\JSON_THROW_ON_ERROR> $flags |
51: | * @return mixed |
52: | */ |
53: | public static function parse(string $json, int $flags = 0) |
54: | { |
55: | return json_decode($json, null, 512, self::DECODE_FLAGS | $flags); |
56: | } |
57: | |
58: | /** |
59: | * Convert a JSON string to a value, returning JSON objects as associative |
60: | * arrays |
61: | * |
62: | * @param int-mask-of<\JSON_BIGINT_AS_STRING|\JSON_INVALID_UTF8_IGNORE|\JSON_INVALID_UTF8_SUBSTITUTE|\JSON_THROW_ON_ERROR> $flags |
63: | * @return mixed[]|int|float|string|bool|null |
64: | */ |
65: | public static function parseObjectAsArray(string $json, int $flags = 0) |
66: | { |
67: | /** @var mixed[]|int|float|string|bool|null */ |
68: | return json_decode($json, true, 512, self::DECODE_FLAGS | $flags); |
69: | } |
70: | } |
71: |