+ /**
+ * Converts a php array to javascript object/array notation (not strict JSON).
+ *
+ * Does not encode keys unless they contain special characters.
+ * Does not encode values by default, so either specify $encodeValues = TRUE,
+ * or pass strings of valid js/json as values (per output from getRawProps).
+ * @see CRM_Utils_JS::getRawProps
+ *
+ * @param array $obj
+ * @param bool $encodeValues
+ * @return string
+ */
+ public static function writeObject($obj, $encodeValues = FALSE) {
+ $js = [];
+ $brackets = isset($obj[0]) && array_keys($obj) === range(0, count($obj) - 1) ? ['[', ']'] : ['{', '}'];
+ foreach ($obj as $key => $val) {
+ if ($encodeValues) {
+ $val = json_encode($val, JSON_UNESCAPED_SLASHES);
+ }
+ if ($brackets[0] == '{') {
+ // Enclose the key in quotes unless it is purely alphanumeric
+ if (preg_match('/\W/', $key)) {
+ // Prefer single quotes
+ $key = preg_match('/^[\w "]+$/', $key) ? "'" . $key . "'" : json_encode($key, JSON_UNESCAPED_SLASHES);
+ }
+ $js[] = "$key: $val";
+ }
+ else {
+ $js[] = $val;
+ }
+ }
+ return $brackets[0] . implode(', ', $js) . $brackets[1];
+ }
+