1: <?php
2:
3: 4: 5: 6: 7:
8:
9:
10:
11: 12: 13: 14: 15: 16:
17: class NJson
18: {
19: const FORCE_ARRAY = 1;
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: 6 => 'Recursion detected',
29: 7 => 'Inf and NaN cannot be JSON encoded',
30: 8 => 'Type is not supported',
31: );
32:
33:
34: 35: 36:
37: final public function __construct()
38: {
39: throw new NStaticClassException;
40: }
41:
42:
43: 44: 45: 46: 47:
48: public static function encode($value)
49: {
50: if (function_exists('ini_set')) {
51: $old = ini_set('display_errors', 0);
52: }
53: set_error_handler(create_function('$severity, $message', ' // needed to receive \'recursion detected\' error
54: restore_error_handler();
55: throw new NJsonException($message);
56: '));
57: $json = json_encode($value);
58: restore_error_handler();
59: if (isset($old)) {
60: ini_set('display_errors', $old);
61: }
62: if (PHP_VERSION_ID >= 50300 && ($error = json_last_error())) {
63: throw new NJsonException(isset(self::$messages[$error]) ? self::$messages[$error] : 'Unknown error', $error);
64: }
65: $json = str_replace(array("\xe2\x80\xa8", "\xe2\x80\xa9"), array('\u2028', '\u2029'), $json);
66: return $json;
67: }
68:
69:
70: 71: 72: 73: 74: 75:
76: public static function decode($json, $options = 0)
77: {
78: $json = (string) $json;
79: if (!preg_match('##u', $json)) {
80: throw new NJsonException(self::$messages[5], 5);
81: }
82:
83: $forceArray = (bool) ($options & self::FORCE_ARRAY);
84: if (!$forceArray && preg_match('#(?<=[^\\\\]")\\\\u0000(?:[^"\\\\]|\\\\.)*+"\s*+:#', $json)) {
85: throw new NJsonException(self::$messages[JSON_ERROR_CTRL_CHAR]);
86: }
87:
88: $value = json_decode($json, $forceArray);
89: if ($value === NULL && $json !== '' && strcasecmp($json, 'null')) {
90: $error = PHP_VERSION_ID >= 50300 ? json_last_error() : 0;
91: throw new NJsonException(isset(self::$messages[$error]) ? self::$messages[$error] : 'Unknown error', $error);
92: }
93: return $value;
94: }
95:
96: }
97:
98:
99: 100: 101: 102:
103: class NJsonException extends Exception
104: {
105: }
106: