BaseJson.php 6.8 KB

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