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: const FORCE_ARRAY = 1;
19: const PRETTY = 2;
20:
21:
22: private static $messages = array(
23: JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
24: JSON_ERROR_STATE_MISMATCH => 'Syntax error, malformed JSON',
25: JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
26: JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
27: 5 => 'Invalid UTF-8 sequence',
28: );
29:
30:
31: 32: 33:
34: final public function __construct()
35: {
36: throw new Nette\StaticClassException;
37: }
38:
39:
40: 41: 42: 43: 44: 45:
46: public static function encode($value, $options = 0)
47: {
48: $flags = PHP_VERSION_ID >= 50400 ? (JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | ($options & self::PRETTY ? JSON_PRETTY_PRINT : 0)) : 0;
49:
50: if (PHP_VERSION_ID < 50500) {
51: $json = Callback::invokeSafe('json_encode', array($value, $flags), function ($message) {
52: throw new JsonException($message);
53: });
54: } else {
55: $json = json_encode($value, $flags);
56: }
57:
58: if ($error = json_last_error()) {
59: $message = isset(static::$messages[$error]) ? static::$messages[$error]
60: : (PHP_VERSION_ID >= 50500 ? json_last_error_msg() : 'Unknown error');
61: throw new JsonException($message, $error);
62: }
63:
64: $json = str_replace(array("\xe2\x80\xa8", "\xe2\x80\xa9"), array('\u2028', '\u2029'), $json);
65: return $json;
66: }
67:
68:
69: 70: 71: 72: 73: 74:
75: public static function decode($json, $options = 0)
76: {
77: $json = (string) $json;
78: if (!preg_match('##u', $json)) {
79: throw new JsonException('Invalid UTF-8 sequence', 5);
80: }
81:
82: $forceArray = (bool) ($options & self::FORCE_ARRAY);
83: if (!$forceArray && preg_match('#(?<=[^\\\\]")\\\\u0000(?:[^"\\\\]|\\\\.)*+"\s*+:#', $json)) {
84: throw new JsonException(static::$messages[JSON_ERROR_CTRL_CHAR]);
85: }
86: $args = array($json, $forceArray, 512);
87: if (PHP_VERSION_ID >= 50400 && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
88: $args[] = JSON_BIGINT_AS_STRING;
89: }
90: $value = call_user_func_array('json_decode', $args);
91:
92: if ($value === NULL && $json !== '' && strcasecmp(trim($json, " \t\n\r"), 'null') !== 0) {
93: $error = json_last_error();
94: throw new JsonException(isset(static::$messages[$error]) ? static::$messages[$error] : 'Unknown error', $error);
95: }
96: return $value;
97: }
98:
99: }
100: