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