Bitrix-D7 22.2
Загрузка...
Поиск...
Не найдено
json.php
См. документацию.
1<?php
2
3namespace Bitrix\Main\Web;
4
9
10class Json
11{
13
24 public static function encode($data, $options = null)
25 {
26 if (!Application::getInstance()->isUtfMode())
27 {
29 $data = self::convertData($data);
30 }
31
32 if (is_null($options))
33 {
34 $options = JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT;
35 }
36
37 $res = json_encode($data, $options);
38
39 self::checkException($options);
40
41 return $res;
42 }
43
53 public static function decode($data)
54 {
55 $res = json_decode($data, true);
56
58
59 // PHP<5.3.3 returns no error for JSON_ERROR_UTF8 and some other ones
60 if($res === null && strtolower($data) != 'null')
61 {
62 self::throwException(self::JSON_ERROR_UNKNOWN);
63 }
64
65 if (!Application::getInstance()->isUtfMode())
66 {
67 $res = self::unConvertData($res);
68 }
69
70 return $res;
71 }
72
79 protected static function serializeJson(&$data)
80 {
81 if($data instanceof \JsonSerializable)
82 {
83 $data = $data->jsonSerialize();
84 }
85
86 if (is_iterable($data))
87 {
88 foreach ($data as $key => $value)
89 {
90 self::serializeJson($data[$key]);
91 }
92 }
93 }
94
101 protected static function convertData($data)
102 {
103 $culture = Context::getCurrent()->getCulture();
104
105 return Encoding::convertEncoding($data, $culture->getCharset(), 'UTF-8');
106 }
107
114 protected static function unConvertData($data)
115 {
116 $culture = Context::getCurrent()->getCulture();
117
118 return Encoding::convertEncoding($data, 'UTF-8', $culture->getCharset());
119 }
120
129 protected static function checkException($options = 0)
130 {
131 $e = json_last_error();
132
133 if ($e == JSON_ERROR_NONE)
134 {
135 return;
136 }
137
138 if ($e == JSON_ERROR_UTF8 && ($options & JSON_PARTIAL_OUTPUT_ON_ERROR))
139 {
140 return;
141 }
142
143 $message = sprintf('%s [%d]', json_last_error_msg(), $e);
144 self::throwException($message);
145 }
146
155 protected static function throwException($e)
156 {
157 throw new ArgumentException('JSON error: '.$e, 'data');
158 }
159}
static getCurrent()
Definition: context.php:245
static throwException($e)
Definition: json.php:155
const JSON_ERROR_UNKNOWN
Definition: json.php:12
static decode($data)
Definition: json.php:53
static serializeJson(&$data)
Definition: json.php:79
static checkException($options=0)
Definition: json.php:129
static convertData($data)
Definition: json.php:101
static unConvertData($data)
Definition: json.php:114
static encode($data, $options=null)
Definition: json.php:24