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