Completed
Pull Request — master (#15527)
by Nikolay
32:09 queued 29:07
created

BaseJson::htmlEncode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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