Index: trunk/phase3/includes/Xml.php |
— | — | @@ -607,19 +607,52 @@ |
608 | 608 | } |
609 | 609 | |
610 | 610 | /** |
611 | | - * Encode a variable of unknown type to JavaScript. If you're not dealing |
612 | | - * with potential instances of XmlJsCode (which bypass encoding), then |
613 | | - * FormatJson::encode should be used directly. |
| 611 | + * Encode a variable of unknown type to JavaScript. |
| 612 | + * Arrays are converted to JS arrays, objects are converted to JS associative |
| 613 | + * arrays (objects). So cast your PHP associative arrays to objects before |
| 614 | + * passing them to here. |
614 | 615 | * |
615 | 616 | * @param $value |
616 | 617 | * |
617 | 618 | * @return string |
618 | 619 | */ |
619 | 620 | public static function encodeJsVar( $value ) { |
620 | | - if ( $value instanceof XmlJsCode ) { |
621 | | - return $value->value; |
| 621 | + if ( is_bool( $value ) ) { |
| 622 | + $s = $value ? 'true' : 'false'; |
| 623 | + } elseif ( is_null( $value ) ) { |
| 624 | + $s = 'null'; |
| 625 | + } elseif ( is_int( $value ) || is_float( $value ) ) { |
| 626 | + $s = strval($value); |
| 627 | + } elseif ( is_array( $value ) && // Make sure it's not associative. |
| 628 | + array_keys($value) === range( 0, count($value) - 1 ) || |
| 629 | + count($value) == 0 |
| 630 | + ) { |
| 631 | + $s = '['; |
| 632 | + foreach ( $value as $elt ) { |
| 633 | + if ( $s != '[' ) { |
| 634 | + $s .= ','; |
| 635 | + } |
| 636 | + $s .= self::encodeJsVar( $elt ); |
| 637 | + } |
| 638 | + $s .= ']'; |
| 639 | + } elseif ( $value instanceof XmlJsCode ) { |
| 640 | + $s = $value->value; |
| 641 | + } elseif ( is_object( $value ) || is_array( $value ) ) { |
| 642 | + // Objects and associative arrays |
| 643 | + $s = '{'; |
| 644 | + foreach ( (array)$value as $name => $elt ) { |
| 645 | + if ( $s != '{' ) { |
| 646 | + $s .= ','; |
| 647 | + } |
| 648 | + |
| 649 | + $s .= '"' . self::escapeJsString( $name ) . '":' . |
| 650 | + self::encodeJsVar( $elt ); |
| 651 | + } |
| 652 | + $s .= '}'; |
| 653 | + } else { |
| 654 | + $s = '"' . self::escapeJsString( $value ) . '"'; |
622 | 655 | } |
623 | | - return FormatJson::encode( $value ); |
| 656 | + return $s; |
624 | 657 | } |
625 | 658 | |
626 | 659 | /** |