Permalink
Browse files

Improvments to getJSObject

	Resources are ignored
	Object keys and strings are encoded with json_encode
	If the input array contains (php) objects, their values are used for recursion rather than the objects themselves (the function takes an array, not an object)
	Less string concatenation, more array implosion
  • Loading branch information...
1 parent 890b4ce commit 0d9e920fad257f07ea01c6a583b3123e132134d7 @okonomiyaki3000 okonomiyaki3000 committed Oct 5, 2012
Showing with 26 additions and 21 deletions.
  1. +26 −21 libraries/joomla/html/html.php
@@ -930,41 +930,46 @@ public static function addIncludePath($path = '')
*/
public static function getJSObject(array $array = array())
{
- $object = '{';
-
- // Iterate over array to build objects
- foreach ((array) $array as $k => $v)
+ $elements = array();
+ foreach ($array as $k => $v)
{
- if (is_null($v))
+ // Don't encode either of these types
+ if (is_null($v) || is_resource($v))
{
continue;
}
+ // Safely encode as a Javascript string
+ $key = json_encode((string) $k);
+
if (is_bool($v))
{
- $object .= ' ' . $k . ': ';
- $object .= ($v) ? 'true' : 'false';
- $object .= ',';
+ $elements[] = $key . ': ' . ($v ? 'true' : 'false');
+ }
+ elseif (is_numeric($v))
+ {
+ $elements[] = $key . ': ' . ($v + 0);
}
- elseif (!is_array($v) && !is_object($v))
+ elseif (is_string($v))
{
- $object .= ' ' . $k . ': ';
- $object .= (is_numeric($v) || strpos($v, '\\') === 0) ? (is_numeric($v)) ? $v : substr($v, 1) : "'" . $v . "'";
- $object .= ',';
+ if (strpos($v, '\\') === 0)
+ {
+ // Items such as functions and JSON objects are prefixed with \, strip the prefix and don't encode them
+ $elements[] = $key . ': ' . substr($v, 1);
+ }
+ else
+ {
+ // The safest way to insert a string
+ $elements[] = $key . ': ' . json_encode((string) $v);
+ }
}
else
{
- $object .= ' ' . $k . ': ' . self::getJSObject($v) . ',';
+ $elements[] = $key . ': ' . self::getJSObject(is_object($v) ? get_object_vars($v) : $v);
}
}
- if (substr($object, -1) == ',')
- {
- $object = substr($object, 0, -1);
- }
-
- $object .= '}';
-
- return $object;
+ return '{' . implode(',', $elements) . '}';
+
}
}

0 comments on commit 0d9e920

Please sign in to comment.