1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13:
14:
15: 16: 17: 18: 19:
20: final class Json
21: {
22: const FORCE_ARRAY = 1;
23:
24:
25: private static $messages = array(
26: JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
27: JSON_ERROR_STATE_MISMATCH => 'Syntax error, malformed JSON',
28: JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
29: JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
30: );
31:
32:
33:
34: 35: 36:
37: final public function __construct()
38: {
39: throw new LogicException("Cannot instantiate static class " . get_class($this));
40: }
41:
42:
43:
44: 45: 46: 47: 48:
49: public static function encode($value)
50: {
51: Debug::tryError();
52: if (function_exists('ini_set')) {
53: $old = ini_set('display_errors', 0); 54: $json = json_encode($value);
55: ini_set('display_errors', $old);
56: } else {
57: $json = json_encode($value);
58: }
59: if (Debug::catchError($e)) { 60: throw new JsonException($e->getMessage());
61: }
62: return $json;
63: }
64:
65:
66:
67: 68: 69: 70: 71: 72:
73: public static function decode($json, $options = 0)
74: {
75: $json = (string) $json;
76: $value = json_decode($json, (bool) ($options & self::FORCE_ARRAY));
77: if ($value === NULL && $json !== '' && strcasecmp($json, 'null')) { 78: $error = PHP_VERSION_ID >= 50300 ? json_last_error() : 0;
79: throw new JsonException(isset(self::$messages[$error]) ? self::$messages[$error] : 'Unknown error', $error);
80: }
81: return $value;
82: }
83:
84: }
85:
86:
87:
88: 89: 90:
91: class JsonException extends Exception
92: {
93: }
94: