Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

174 rindas
6.4KB

  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. * The method enhances `json_encode()` by supporting JavaScript expressions.
  39. * In particular, the method will not encode a JavaScript expression that is
  40. * represented in terms of a [[JsExpression]] object.
  41. * @param mixed $value the data to be encoded.
  42. * @param integer $options the encoding options. For more details please refer to
  43. * <http://www.php.net/manual/en/function.json-encode.php>. Default is `JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE`.
  44. * @return string the encoding result.
  45. * @throws InvalidParamException if there is any encoding error.
  46. */
  47. public static function encode($value, $options = 320)
  48. {
  49. $expressions = [];
  50. $value = static::processData($value, $expressions, uniqid('', true));
  51. set_error_handler(function () {
  52. static::handleJsonError(JSON_ERROR_SYNTAX);
  53. }, E_WARNING);
  54. $json = json_encode($value, $options);
  55. restore_error_handler();
  56. static::handleJsonError(json_last_error());
  57. return $expressions === [] ? $json : strtr($json, $expressions);
  58. }
  59. /**
  60. * Encodes the given value into a JSON string HTML-escaping entities so it is safe to be embedded in HTML code.
  61. * The method enhances `json_encode()` by supporting JavaScript expressions.
  62. * In particular, the method will not encode a JavaScript expression that is
  63. * represented in terms of a [[JsExpression]] object.
  64. *
  65. * @param mixed $value the data to be encoded
  66. * @return string the encoding result
  67. * @since 2.0.4
  68. * @throws InvalidParamException if there is any encoding error
  69. */
  70. public static function htmlEncode($value)
  71. {
  72. return static::encode($value, JSON_UNESCAPED_UNICODE | JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS);
  73. }
  74. /**
  75. * Decodes the given JSON string into a PHP data structure.
  76. * @param string $json the JSON string to be decoded
  77. * @param boolean $asArray whether to return objects in terms of associative arrays.
  78. * @return mixed the PHP data
  79. * @throws InvalidParamException if there is any decoding error
  80. */
  81. public static function decode($json, $asArray = true)
  82. {
  83. if (is_array($json)) {
  84. throw new InvalidParamException('Invalid JSON data.');
  85. } elseif ($json === null || $json === '') {
  86. return null;
  87. }
  88. $decode = json_decode((string) $json, $asArray);
  89. static::handleJsonError(json_last_error());
  90. return $decode;
  91. }
  92. /**
  93. * Handles [[encode()]] and [[decode()]] errors by throwing exceptions with the respective error message.
  94. *
  95. * @param integer $lastError error code from [json_last_error()](http://php.net/manual/en/function.json-last-error.php).
  96. * @throws \yii\base\InvalidParamException if there is any encoding/decoding error.
  97. * @since 2.0.6
  98. */
  99. protected static function handleJsonError($lastError)
  100. {
  101. if ($lastError === JSON_ERROR_NONE) {
  102. return;
  103. }
  104. $availableErrors = [];
  105. foreach (static::$jsonErrorMessages as $const => $message) {
  106. if (defined($const)) {
  107. $availableErrors[constant($const)] = $message;
  108. }
  109. }
  110. if (isset($availableErrors[$lastError])) {
  111. throw new InvalidParamException($availableErrors[$lastError], $lastError);
  112. }
  113. throw new InvalidParamException('Unknown JSON encoding/decoding error.');
  114. }
  115. /**
  116. * Pre-processes the data before sending it to `json_encode()`.
  117. * @param mixed $data the data to be processed
  118. * @param array $expressions collection of JavaScript expressions
  119. * @param string $expPrefix a prefix internally used to handle JS expressions
  120. * @return mixed the processed data
  121. */
  122. protected static function processData($data, &$expressions, $expPrefix)
  123. {
  124. if (is_object($data)) {
  125. if ($data instanceof JsExpression) {
  126. $token = "!{[$expPrefix=" . count($expressions) . ']}!';
  127. $expressions['"' . $token . '"'] = $data->expression;
  128. return $token;
  129. } elseif ($data instanceof \JsonSerializable) {
  130. return static::processData($data->jsonSerialize(), $expressions, $expPrefix);
  131. } elseif ($data instanceof Arrayable) {
  132. $data = $data->toArray();
  133. } elseif ($data instanceof \SimpleXMLElement) {
  134. $data = (array) $data;
  135. } else {
  136. $result = [];
  137. foreach ($data as $name => $value) {
  138. $result[$name] = $value;
  139. }
  140. $data = $result;
  141. }
  142. if ($data === []) {
  143. return new \stdClass();
  144. }
  145. }
  146. if (is_array($data)) {
  147. foreach ($data as $key => $value) {
  148. if (is_array($value) || is_object($value)) {
  149. $data[$key] = static::processData($value, $expressions, $expPrefix);
  150. }
  151. }
  152. }
  153. return $data;
  154. }
  155. }