1: <?php
2:
3: 4: 5: 6:
7:
8: namespace Nette\Utils;
9:
10: use Nette;
11:
12:
13: 14: 15:
16: class Json
17: {
18: use Nette\StaticClass;
19:
20: const FORCE_ARRAY = 0b0001;
21: const PRETTY = 0b0010;
22:
23:
24: 25: 26: 27: 28: 29:
30: public static function encode($value, $options = 0)
31: {
32: $flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
33: | ($options & self::PRETTY ? JSON_PRETTY_PRINT : 0)
34: | (defined('JSON_PRESERVE_ZERO_FRACTION') ? JSON_PRESERVE_ZERO_FRACTION : 0);
35:
36: $json = json_encode($value, $flags);
37: if ($error = json_last_error()) {
38: throw new JsonException(json_last_error_msg(), $error);
39: }
40:
41: $json = str_replace(["\xe2\x80\xa8", "\xe2\x80\xa9"], ['\u2028', '\u2029'], $json);
42: return $json;
43: }
44:
45:
46: 47: 48: 49: 50: 51:
52: public static function decode($json, $options = 0)
53: {
54: $json = (string) $json;
55: if (defined('JSON_C_VERSION') && !preg_match('##u', $json)) {
56: throw new JsonException('Invalid UTF-8 sequence', 5);
57: } elseif ($json === '') {
58: throw new JsonException('Syntax error');
59: }
60:
61: $forceArray = (bool) ($options & self::FORCE_ARRAY);
62: if (PHP_VERSION_ID < 70000 && !$forceArray && preg_match('#(?<=[^\\\\]")\\\\u0000(?:[^"\\\\]|\\\\.)*+"\s*+:#', $json)) {
63: throw new JsonException('The decoded property name is invalid');
64: }
65: $flags = !defined('JSON_C_VERSION') || PHP_INT_SIZE === 4 ? JSON_BIGINT_AS_STRING : 0;
66:
67: $value = json_decode($json, $forceArray, 512, $flags);
68: if ($error = json_last_error()) {
69: throw new JsonException(json_last_error_msg(), $error);
70: }
71: return $value;
72: }
73:
74: }
75: