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:
23: final class Json
24: {
25: const FORCE_ARRAY = 1;
26:
27:
28: private static $messages = array(
29: JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
30: JSON_ERROR_STATE_MISMATCH => 'Syntax error, malformed JSON',
31: JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
32: JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
33: );
34:
35:
36:
37: 38: 39:
40: final public function __construct()
41: {
42: throw new Nette\StaticClassException;
43: }
44:
45:
46:
47: 48: 49: 50: 51:
52: public static function encode($value)
53: {
54: Nette\Diagnostics\Debugger::tryError();
55: if (function_exists('ini_set')) {
56: $old = ini_set('display_errors', 0);
57: $json = json_encode($value);
58: ini_set('display_errors', $old);
59: } else {
60: $json = json_encode($value);
61: }
62: if (Nette\Diagnostics\Debugger::catchError($e)) {
63: throw new JsonException($e->getMessage());
64: }
65: return $json;
66: }
67:
68:
69:
70: 71: 72: 73: 74: 75:
76: public static function decode($json, $options = 0)
77: {
78: $json = (string) $json;
79: $value = json_decode($json, (bool) ($options & self::FORCE_ARRAY));
80: if ($value === NULL && $json !== '' && strcasecmp($json, 'null')) {
81: $error = PHP_VERSION_ID >= 50300 ? json_last_error() : 0;
82: throw new JsonException(isset(static::$messages[$error]) ? static::$messages[$error] : 'Unknown error', $error);
83: }
84: return $value;
85: }
86:
87: }
88:
89:
90:
91: 92: 93:
94: class JsonException extends \Exception
95: {
96: }
97: