<?php
function writeJavaScriptConstants($constants, $pathToJs, $fileName='constants.js', $prefix='Core.Constants') {
// does the file exist already
if (is_file($pathToJs . DIRECTORY_SEPARATOR . $fileName)) {
unlink($pathToJs . DIRECTORY_SEPARATOR . $fileName);
}
$rs = fopen($pathToJs . DIRECTORY_SEPARATOR . $fileName, 'wb');
$objExists = array();
$typeExists = array();
$i = 1;
$sb = array($prefix . '={};');
foreach ($constants as $k => $v) {
$keys = explode('_', $k);
$obj = strtolower($keys[0]);
$type = strtolower($keys[1]);
$name = strtoupper(implode('_', array_slice($keys, 2)));
// the object has not been attached in JavaScript, so attach it now
if (FALSE === array_search($obj, $objExists)) {
$sb[$i] = $prefix . '.' . $obj . '={};';
array_push($objExists, $obj);
$i += 1;
}
// the object type has not been attached in JavaScript, so attach it now
if (FALSE === array_search($obj . '.' . $type, $typeExists)) {
$sb[$i] = $prefix . '.' . $obj . '.' . $type . '={};';
array_push($typeExists, $obj . '.' . $type);
$i += 1;
}
$sb[$i] = $prefix . '.' . $obj . '.' . $type . '.' . $name . '=' . (is_string($v) ? "'" . $v . "'" : $v) . ';';
$i += 1;
}
fwrite($rs, implode("\n", $sb));
}
?>