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