[Xml::encodeJsVar] Use FormatJson::encode / native json_encode instead
authorKrinkle <krinkle@users.mediawiki.org>
Mon, 30 Jan 2012 19:45:38 +0000 (19:45 +0000)
committerKrinkle <krinkle@users.mediawiki.org>
Mon, 30 Jan 2012 19:45:38 +0000 (19:45 +0000)
* Follows-up r110320
* XmlTest.php passes

includes/Xml.php

index 7e5b3cd..f866ff0 100644 (file)
@@ -607,52 +607,19 @@ class Xml {
        }
 
        /**
-        * Encode a variable of unknown type to JavaScript.
-        * Arrays are converted to JS arrays, objects are converted to JS associative
-        * arrays (objects). So cast your PHP associative arrays to objects before
-        * passing them to here.
+        * Encode a variable of unknown type to JavaScript. If you're not dealing
+        * with potential instances of XmlJsCode (which bypass encoding), then
+        * FormatJson::encode should be used directly.
         *
         * @param $value
         *
         * @return string
         */
        public static function encodeJsVar( $value ) {
-               if ( is_bool( $value ) ) {
-                       $s = $value ? 'true' : 'false';
-               } elseif ( is_null( $value ) ) {
-                       $s = 'null';
-               } elseif ( is_int( $value ) || is_float( $value ) ) {
-                       $s = strval($value);
-               } elseif ( is_array( $value ) && // Make sure it's not associative.
-                                       array_keys($value) === range( 0, count($value) - 1 ) ||
-                                       count($value) == 0
-                               ) {
-                       $s = '[';
-                       foreach ( $value as $elt ) {
-                               if ( $s != '[' ) {
-                                       $s .= ',';
-                               }
-                               $s .= self::encodeJsVar( $elt );
-                       }
-                       $s .= ']';
-               } elseif ( $value instanceof XmlJsCode ) {
-                       $s = $value->value;
-               } elseif ( is_object( $value ) || is_array( $value ) ) {
-                       // Objects and associative arrays
-                       $s = '{';
-                       foreach ( (array)$value as $name => $elt ) {
-                               if ( $s != '{' ) {
-                                       $s .= ',';
-                               }
-
-                               $s .= '"' . self::escapeJsString( $name ) . '":' .
-                                       self::encodeJsVar( $elt );
-                       }
-                       $s .= '}';
-               } else {
-                       $s = '"' . self::escapeJsString( $value ) . '"';
+               if ( $value instanceof XmlJsCode ) {
+                       return $value->value;
                }
-               return $s;
+               return FormatJson::encode( $value );
        }
 
        /**