Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
93.75% covered (success)
93.75%
15 / 16
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
HtmlJsCode
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
2 / 2
8
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 encodeObject
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
7
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\Html;
8
9/**
10 * A wrapper class which causes Html::encodeJsVar() and Html::encodeJsCall()
11 * (as well as their Xml::* counterparts) to interpret a given string as being
12 * a JavaScript expression, instead of string data.
13 *
14 * @par Example:
15 * @code
16 *     Html::encodeJsVar( new HtmlJsCode( 'a + b' ) );
17 * @endcode
18 *
19 * This returns "a + b".
20 *
21 * @note As of 1.21, HtmlJsCode objects cannot be nested inside objects or arrays. The sole
22 *       exception is the $args argument to Html::encodeJsCall() because Html::encodeJsVar() is
23 *       called for each individual element in that array. If you need to encode an object or array
24 *       containing HtmlJsCode objects, use HtmlJsCode::encodeObject() to re-encode it first.
25 *
26 * @since 1.41 (renamed from XmlJsCode, which existed since 1.17)
27 */
28class HtmlJsCode {
29    public function __construct(
30        public readonly string $value,
31    ) {
32    }
33
34    /**
35     * Encode an object containing HtmlJsCode objects.
36     *
37     * This takes an object or associative array where (some of) the values are HtmlJsCode objects,
38     * and re-encodes it as a single HtmlJsCode object.
39     *
40     * @since 1.33
41     * @phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
42     * @param object|array $obj Object or associative array to encode
43     * @param bool $pretty If true, add non-significant whitespace to improve readability.
44     * @return self
45     */
46    public static function encodeObject( $obj, $pretty = false ) {
47        $parts = [];
48        foreach ( $obj as $key => $value ) {
49            $parts[] =
50                ( $pretty ? '    ' : '' ) .
51                Html::encodeJsVar( $key, $pretty ) .
52                ( $pretty ? ': ' : ':' ) .
53                Html::encodeJsVar( $value, $pretty );
54        }
55        return new self(
56            '{' .
57            ( $pretty ? "\n" : '' ) .
58            implode( $pretty ? ",\n" : ',', $parts ) .
59            ( $pretty ? "\n" : '' ) .
60            '}'
61        );
62    }
63}
64
65/** @deprecated class alias since 1.41 */
66class_alias( HtmlJsCode::class, 'XmlJsCode' );