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: const PRETTY = 2;
22:
23:
24: private static $messages = array(
25: JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
26: JSON_ERROR_STATE_MISMATCH => 'Syntax error, malformed JSON',
27: JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
28: JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
29: 5 => 'Invalid UTF-8 sequence',
30: );
31:
32:
33: 34: 35:
36: final public function __construct()
37: {
38: throw new Nette\StaticClassException;
39: }
40:
41:
42: 43: 44: 45: 46: 47:
48: public static function encode($value, $options = 0)
49: {
50: if (PHP_VERSION_ID < 50500) {
51: set_error_handler(function($severity, $message) {
52: restore_error_handler();
53: throw new JsonException($message);
54: });
55: }
56:
57: $json = json_encode(
58: $value,
59: PHP_VERSION_ID >= 50400 ? (JSON_UNESCAPED_UNICODE | ($options & self::PRETTY ? JSON_PRETTY_PRINT : 0)) : 0
60: );
61:
62: if (PHP_VERSION_ID < 50500) {
63: restore_error_handler();
64: }
65: if ($error = json_last_error()) {
66: $message = isset(static::$messages[$error]) ? static::$messages[$error]
67: : (PHP_VERSION_ID >= 50500 ? json_last_error_msg() : 'Unknown error');
68: throw new JsonException($message, $error);
69: }
70:
71: $json = str_replace(array("\xe2\x80\xa8", "\xe2\x80\xa9"), array('\u2028', '\u2029'), $json);
72: return $json;
73: }
74:
75:
76: 77: 78: 79: 80: 81:
82: public static function decode($json, $options = 0)
83: {
84: $json = (string) $json;
85: if (!preg_match('##u', $json)) {
86: throw new JsonException('Invalid UTF-8 sequence', 5);
87: }
88:
89: $args = array($json, (bool) ($options & self::FORCE_ARRAY));
90: $args[] = 512;
91: if (PHP_VERSION_ID >= 50400 && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
92: $args[] = JSON_BIGINT_AS_STRING;
93: }
94: $value = call_user_func_array('json_decode', $args);
95:
96: if ($value === NULL && $json !== '' && strcasecmp($json, 'null')) {
97: $error = json_last_error();
98: throw new JsonException(isset(static::$messages[$error]) ? static::$messages[$error] : 'Unknown error', $error);
99: }
100: return $value;
101: }
102:
103: }
104:
105:
106: 107: 108:
109: class JsonException extends \Exception
110: {
111: }
112: