1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13:
14:
15: 16: 17: 18: 19: 20:
21: final class Json
22: {
23: const FORCE_ARRAY = 1;
24:
25:
26: private static $messages = array(
27: JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
28: JSON_ERROR_STATE_MISMATCH => 'Syntax error, malformed JSON',
29: JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
30: JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
31: 5 => 'Invalid UTF-8 sequence',
32: 6 => 'Recursion detected',
33: 7 => 'Inf and NaN cannot be JSON encoded',
34: 8 => 'Type is not supported',
35: );
36:
37:
38: 39: 40:
41: final public function __construct()
42: {
43: throw new StaticClassException;
44: }
45:
46:
47: 48: 49: 50: 51:
52: public static function encode($value)
53: {
54: if (function_exists('ini_set')) {
55: $old = ini_set('display_errors', 0);
56: }
57: set_error_handler(create_function('$severity, $message', ' // needed to receive \'recursion detected\' error
58: restore_error_handler();
59: throw new JsonException($message);
60: '));
61: $json = json_encode($value);
62: restore_error_handler();
63: if (isset($old)) {
64: ini_set('display_errors', $old);
65: }
66: if (PHP_VERSION_ID >= 50300 && ($error = json_last_error())) {
67: throw new JsonException(isset(self::$messages[$error]) ? self::$messages[$error] : 'Unknown error', $error);
68: }
69: $json = str_replace(array("\xe2\x80\xa8", "\xe2\x80\xa9"), array('\u2028', '\u2029'), $json);
70: return $json;
71: }
72:
73:
74: 75: 76: 77: 78: 79:
80: public static function decode($json, $options = 0)
81: {
82: $json = (string) $json;
83: $value = json_decode($json, (bool) ($options & self::FORCE_ARRAY));
84: if ($value === NULL && $json !== '' && strcasecmp($json, 'null')) {
85: $error = PHP_VERSION_ID >= 50300 ? json_last_error() : 0;
86: throw new JsonException(isset(self::$messages[$error]) ? self::$messages[$error] : 'Unknown error', $error);
87: }
88: return $value;
89: }
90:
91: }
92:
93:
94: 95: 96: 97:
98: class JsonException extends Exception
99: {
100: }
101: