Debian Codegraph @

includes/Html/HtmlJsCode.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Html;
22
23 /**
24 * A wrapper class which causes Html::encodeJsVar() and Html::encodeJsCall()
25 * (as well as their Xml::* counterparts) to interpret a given string as being
26 * a JavaScript expression, instead of string data.
27 *
28 * @par Example:
29 * @code
30 * Html::encodeJsVar( new HtmlJsCode( 'a + b' ) );
31 * @endcode
32 *
33 * This returns "a + b".
34 *
35 * @note As of 1.21, HtmlJsCode objects cannot be nested inside objects or arrays. The sole
36 * exception is the $args argument to Html::encodeJsCall() because Html::encodeJsVar() is
37 * called for each individual element in that array. If you need to encode an object or array
38 * containing HtmlJsCode objects, use HtmlJsCode::encodeObject() to re-encode it first.
39 *
40 * @since 1.41 (renamed from XmlJsCode, which existed since 1.17)
41 */
42 class HtmlJsCode {
43 /** @var string */
44 public $value;
45
46 public function __construct( $value ) {
47 $this->value = $value;
48 }
49
50 /**
51 * Encode an object containing HtmlJsCode objects.
52 *
53 * This takes an object or associative array where (some of) the values are HtmlJsCode objects,
54 * and re-encodes it as a single HtmlJsCode object.
55 *
56 * @since 1.33
57 * @phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
58 * @param object|array $obj Object or associative array to encode
59 * @param bool $pretty If true, add non-significant whitespace to improve readability.
60 * @return HtmlJsCode
61 */
62 public static function encodeObject( $obj, $pretty = false ) {
63 $parts = [];
64 foreach ( $obj as $key => $value ) {
65 $parts[] =
66 ( $pretty ? ' ' : '' ) .
67 Html::encodeJsVar( $key, $pretty ) .
68 ( $pretty ? ': ' : ':' ) .
69 Html::encodeJsVar( $value, $pretty );
70 }
71 return new self(
72 '{' .
73 ( $pretty ? "\n" : '' ) .
74 implode( $pretty ? ",\n" : ',', $parts ) .
75 ( $pretty ? "\n" : '' ) .
76 '}'
77 );
78 }
79 }
80
81 /** @deprecated class alias since 1.41 */
82 class_alias( HtmlJsCode::class, 'XmlJsCode' );