Split parser related files to have one class in one file
[lhc/web/wiklou.git] / includes / XmlJsCode.php
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 /**
22 * A wrapper class which causes Xml::encodeJsVar() and Xml::encodeJsCall() to
23 * interpret a given string as being a JavaScript expression, instead of string
24 * data.
25 *
26 * @par Example:
27 * @code
28 * Xml::encodeJsVar( new XmlJsCode( 'a + b' ) );
29 * @endcode
30 *
31 * This returns "a + b".
32 *
33 * @note As of 1.21, XmlJsCode objects cannot be nested inside objects or arrays. The sole
34 * exception is the $args argument to Xml::encodeJsCall() because Xml::encodeJsVar() is
35 * called for each individual element in that array. If you need to encode an object or array
36 * containing XmlJsCode objects, use XmlJsCode::encodeObject() to re-encode it first.
37 *
38 * @since 1.17
39 */
40 class XmlJsCode {
41 public $value;
42
43 function __construct( $value ) {
44 $this->value = $value;
45 }
46
47 /**
48 * Encode an object containing XmlJsCode objects.
49 *
50 * This takes an object or associative array where (some of) the values are XmlJsCode objects,
51 * and re-encodes it as a single XmlJsCode object.
52 *
53 * @since 1.33
54 * @param object|array $obj Object or associative array to encode
55 * @param bool $pretty If true, add non-significant whitespace to improve readability.
56 * @return XmlJsCode
57 */
58 public static function encodeObject( $obj, $pretty = false ) {
59 $parts = [];
60 foreach ( $obj as $key => $value ) {
61 $parts[] =
62 ( $pretty ? ' ' : '' ) .
63 Xml::encodeJsVar( $key, $pretty ) .
64 ( $pretty ? ': ' : ':' ) .
65 Xml::encodeJsVar( $value, $pretty );
66 }
67 return new self(
68 '{' .
69 ( $pretty ? "\n" : '' ) .
70 implode( $pretty ? ",\n" : ',', $parts ) .
71 ( $pretty ? "\n" : '' ) .
72 '}'
73 );
74 }
75 }