Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
93.75% |
15 / 16 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| HtmlJsCode | |
100.00% |
15 / 15 |
|
100.00% |
2 / 2 |
8 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| encodeObject | |
100.00% |
14 / 14 |
|
100.00% |
1 / 1 |
7 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * @license GPL-2.0-or-later |
| 4 | * @file |
| 5 | */ |
| 6 | |
| 7 | namespace 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 | */ |
| 28 | class HtmlJsCode { |
| 29 | public string $value; |
| 30 | |
| 31 | public function __construct( string $value ) { |
| 32 | $this->value = $value; |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * Encode an object containing HtmlJsCode objects. |
| 37 | * |
| 38 | * This takes an object or associative array where (some of) the values are HtmlJsCode objects, |
| 39 | * and re-encodes it as a single HtmlJsCode object. |
| 40 | * |
| 41 | * @since 1.33 |
| 42 | * @phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam |
| 43 | * @param object|array $obj Object or associative array to encode |
| 44 | * @param bool $pretty If true, add non-significant whitespace to improve readability. |
| 45 | * @return self |
| 46 | */ |
| 47 | public static function encodeObject( $obj, $pretty = false ) { |
| 48 | $parts = []; |
| 49 | foreach ( $obj as $key => $value ) { |
| 50 | $parts[] = |
| 51 | ( $pretty ? ' ' : '' ) . |
| 52 | Html::encodeJsVar( $key, $pretty ) . |
| 53 | ( $pretty ? ': ' : ':' ) . |
| 54 | Html::encodeJsVar( $value, $pretty ); |
| 55 | } |
| 56 | return new self( |
| 57 | '{' . |
| 58 | ( $pretty ? "\n" : '' ) . |
| 59 | implode( $pretty ? ",\n" : ',', $parts ) . |
| 60 | ( $pretty ? "\n" : '' ) . |
| 61 | '}' |
| 62 | ); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | /** @deprecated class alias since 1.41 */ |
| 67 | class_alias( HtmlJsCode::class, 'XmlJsCode' ); |