BaseJson.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\helpers;
  8. use yii\base\Arrayable;
  9. use yii\base\InvalidArgumentException;
  10. use yii\web\JsExpression;
  11. use yii\base\Model;
  12. /**
  13. * BaseJson provides concrete implementation for [[Json]].
  14. *
  15. * Do not use BaseJson. Use [[Json]] instead.
  16. *
  17. * @author Qiang Xue <qiang.xue@gmail.com>
  18. * @since 2.0
  19. */
  20. class BaseJson
  21. {
  22. /**
  23. * List of JSON Error messages assigned to constant names for better handling of version differences.
  24. * @var array
  25. * @since 2.0.7
  26. */
  27. public static $jsonErrorMessages = [
  28. 'JSON_ERROR_DEPTH' => 'The maximum stack depth has been exceeded.',
  29. 'JSON_ERROR_STATE_MISMATCH' => 'Invalid or malformed JSON.',
  30. 'JSON_ERROR_CTRL_CHAR' => 'Control character error, possibly incorrectly encoded.',
  31. 'JSON_ERROR_SYNTAX' => 'Syntax error.',
  32. 'JSON_ERROR_UTF8' => 'Malformed UTF-8 characters, possibly incorrectly encoded.', // PHP 5.3.3
  33. 'JSON_ERROR_RECURSION' => 'One or more recursive references in the value to be encoded.', // PHP 5.5.0
  34. 'JSON_ERROR_INF_OR_NAN' => 'One or more NAN or INF values in the value to be encoded', // PHP 5.5.0
  35. 'JSON_ERROR_UNSUPPORTED_TYPE' => 'A value of a type that cannot be encoded was given', // PHP 5.5.0
  36. ];
  37. /**
  38. * Encodes the given value into a JSON string.
  39. *
  40. * The method enhances `json_encode()` by supporting JavaScript expressions.
  41. * In particular, the method will not encode a JavaScript expression that is
  42. * represented in terms of a [[JsExpression]] object.
  43. *
  44. * Note that data encoded as JSON must be UTF-8 encoded according to the JSON specification.
  45. * You must ensure strings passed to this method have proper encoding before passing them.
  46. *
  47. * @param mixed $value the data to be encoded.
  48. * @param int $options the encoding options. For more details please refer to
  49. * <https://secure.php.net/manual/en/function.json-encode.php>. Default is `JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE`.
  50. * @return string the encoding result.
  51. * @throws InvalidArgumentException if there is any encoding error.
  52. */
  53. public static function encode($value, $options = 320)
  54. {
  55. $expressions = [];
  56. $value = static::processData($value, $expressions, uniqid('', true));
  57. set_error_handler(function () {
  58. static::handleJsonError(JSON_ERROR_SYNTAX);
  59. }, E_WARNING);
  60. $json = json_encode($value, $options);
  61. restore_error_handler();
  62. static::handleJsonError(json_last_error());
  63. return $expressions === [] ? $json : strtr($json, $expressions);
  64. }
  65. /**
  66. * Encodes the given value into a JSON string HTML-escaping entities so it is safe to be embedded in HTML code.
  67. *
  68. * The method enhances `json_encode()` by supporting JavaScript expressions.
  69. * In particular, the method will not encode a JavaScript expression that is
  70. * represented in terms of a [[JsExpression]] object.
  71. *
  72. * Note that data encoded as JSON must be UTF-8 encoded according to the JSON specification.
  73. * You must ensure strings passed to this method have proper encoding before passing them.
  74. *
  75. * @param mixed $value the data to be encoded
  76. * @return string the encoding result
  77. * @since 2.0.4
  78. * @throws InvalidArgumentException if there is any encoding error
  79. */
  80. public static function htmlEncode($value)
  81. {
  82. return static::encode($value, JSON_UNESCAPED_UNICODE | JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS);
  83. }
  84. /**
  85. * Decodes the given JSON string into a PHP data structure.
  86. * @param string $json the JSON string to be decoded
  87. * @param bool $asArray whether to return objects in terms of associative arrays.
  88. * @return mixed the PHP data
  89. * @throws InvalidArgumentException if there is any decoding error
  90. */
  91. public static function decode($json, $asArray = true)
  92. {
  93. if (is_array($json)) {
  94. throw new InvalidArgumentException('Invalid JSON data.');
  95. } elseif ($json === null || $json === '') {
  96. return null;
  97. }
  98. $decode = json_decode((string) $json, $asArray);
  99. static::handleJsonError(json_last_error());
  100. return $decode;
  101. }
  102. /**
  103. * Handles [[encode()]] and [[decode()]] errors by throwing exceptions with the respective error message.
  104. *
  105. * @param int $lastError error code from [json_last_error()](https://secure.php.net/manual/en/function.json-last-error.php).
  106. * @throws InvalidArgumentException if there is any encoding/decoding error.
  107. * @since 2.0.6
  108. */
  109. protected static function handleJsonError($lastError)
  110. {
  111. if ($lastError === JSON_ERROR_NONE) {
  112. return;
  113. }
  114. $availableErrors = [];
  115. foreach (static::$jsonErrorMessages as $const => $message) {
  116. if (defined($const)) {
  117. $availableErrors[constant($const)] = $message;
  118. }
  119. }
  120. if (isset($availableErrors[$lastError])) {
  121. throw new InvalidArgumentException($availableErrors[$lastError], $lastError);
  122. }
  123. throw new InvalidArgumentException('Unknown JSON encoding/decoding error.');
  124. }
  125. /**
  126. * Pre-processes the data before sending it to `json_encode()`.
  127. * @param mixed $data the data to be processed
  128. * @param array $expressions collection of JavaScript expressions
  129. * @param string $expPrefix a prefix internally used to handle JS expressions
  130. * @return mixed the processed data
  131. */
  132. protected static function processData($data, &$expressions, $expPrefix)
  133. {
  134. if (is_object($data)) {
  135. if ($data instanceof JsExpression) {
  136. $token = "!{[$expPrefix=" . count($expressions) . ']}!';
  137. $expressions['"' . $token . '"'] = $data->expression;
  138. return $token;
  139. } elseif ($data instanceof \JsonSerializable) {
  140. return static::processData($data->jsonSerialize(), $expressions, $expPrefix);
  141. } elseif ($data instanceof Arrayable) {
  142. $data = $data->toArray();
  143. } elseif ($data instanceof \SimpleXMLElement) {
  144. $data = (array) $data;
  145. } else {
  146. $result = [];
  147. foreach ($data as $name => $value) {
  148. $result[$name] = $value;
  149. }
  150. $data = $result;
  151. }
  152. if ($data === []) {
  153. return new \stdClass();
  154. }
  155. }
  156. if (is_array($data)) {
  157. foreach ($data as $key => $value) {
  158. if (is_array($value) || is_object($value)) {
  159. $data[$key] = static::processData($value, $expressions, $expPrefix);
  160. }
  161. }
  162. }
  163. return $data;
  164. }
  165. /**
  166. * Generates a summary of the validation errors.
  167. * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
  168. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  169. *
  170. * - showAllErrors: boolean, if set to true every error message for each attribute will be shown otherwise
  171. * only the first error message for each attribute will be shown. Defaults to `false`.
  172. *
  173. * @return string the generated error summary
  174. * @since 2.0.14
  175. */
  176. public static function errorSummary($models, $options = [])
  177. {
  178. $showAllErrors = ArrayHelper::remove($options, 'showAllErrors', false);
  179. $lines = self::collectErrors($models, $showAllErrors);
  180. return json_encode($lines);
  181. }
  182. /**
  183. * Return array of the validation errors
  184. * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
  185. * @param $showAllErrors boolean, if set to true every error message for each attribute will be shown otherwise
  186. * only the first error message for each attribute will be shown.
  187. * @return array of the validation errors
  188. * @since 2.0.14
  189. */
  190. private static function collectErrors($models, $showAllErrors)
  191. {
  192. $lines = [];
  193. if (!is_array($models)) {
  194. $models = [$models];
  195. }
  196. foreach ($models as $model) {
  197. $lines = array_unique(array_merge($lines, $model->getErrorSummary($showAllErrors)));
  198. }
  199. return $lines;
  200. }
  201. }