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: if (PHP_VERSION_ID < 70100) {
42: $json = str_replace(["\xe2\x80\xa8", "\xe2\x80\xa9"], ['\u2028', '\u2029'], $json);
43: }
44:
45: return $json;
46: }
47:
48:
49: 50: 51: 52: 53: 54:
55: public static function decode($json, $options = 0)
56: {
57: $forceArray = (bool) ($options & self::FORCE_ARRAY);
58: $flags = JSON_BIGINT_AS_STRING;
59:
60: if (PHP_VERSION_ID < 70000) {
61: $json = (string) $json;
62: if ($json === '') {
63: throw new JsonException('Syntax error');
64: } elseif (!$forceArray && preg_match('#(?<=[^\\\\]")\\\\u0000(?:[^"\\\\]|\\\\.)*+"\s*+:#', $json)) {
65: throw new JsonException('The decoded property name is invalid');
66: } elseif (defined('JSON_C_VERSION') && !preg_match('##u', $json)) {
67: throw new JsonException('Invalid UTF-8 sequence', 5);
68: } elseif (defined('JSON_C_VERSION') && PHP_INT_SIZE === 8) {
69: $flags &= ~JSON_BIGINT_AS_STRING;
70: }
71: }
72:
73: $value = json_decode($json, $forceArray, 512, $flags);
74: if ($error = json_last_error()) {
75: throw new JsonException(json_last_error_msg(), $error);
76: }
77:
78: return $value;
79: }
80: }
81: