refactor: modest speedup to database config population (#6636)

use references to assign values into the config array more efficiently, prevents a lot of memory churn caused by the recursive approach
This commit is contained in:
Tony Murray
2017-05-13 13:54:53 -05:00
committed by Neil Lathwood
parent 1ce58cd33d
commit 595e75bd14

View File

@ -33,41 +33,39 @@ function mergedb()
{
global $config;
$clone = $config;
foreach (dbFetchRows('select config_name,config_value from config') as $obj) {
$clone = array_replace_recursive($clone, mergecnf($obj));
$db_config = array();
foreach (dbFetchRows('SELECT `config_name`,`config_value` FROM `config`') as $obj) {
assign_array_by_path($db_config, $obj['config_name'], $obj['config_value']);
}
$config = array_replace_recursive($clone, $config);
$config = array_replace_recursive($db_config, $config);
}
/**
* @param $obj
* @return array
* Assign a value into the passed array by a path
* 'snmp.version' = 'v1' becomes $arr['snmp']['version'] = 'v1'
*
* @param array $arr the array to insert the value into, will be modified in place
* @param string $path the path to insert the value at
* @param mixed $value the value to insert, will be type cast
* @param string $separator path separator
*/
function mergecnf($obj)
function assign_array_by_path(&$arr, $path, $value, $separator = '.')
{
$pointer = array();
$val = $obj['config_value'];
$obj = $obj['config_name'];
$obj = explode('.', $obj, 2);
if (!isset($obj[1])) {
if (filter_var($val, FILTER_VALIDATE_INT)) {
$val = (int) $val;
} elseif (filter_var($val, FILTER_VALIDATE_FLOAT)) {
$val = (float) $val;
} elseif (filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) !== null) {
$val = filter_var($val, FILTER_VALIDATE_BOOLEAN);
// type cast value. Is this needed here?
if (filter_var($value, FILTER_VALIDATE_INT)) {
$value = (int) $value;
} elseif (filter_var($value, FILTER_VALIDATE_FLOAT)) {
$value = (float) $value;
} elseif (filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) !== null) {
$value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
}
if (!empty($obj[0])) {
return array($obj[0] => $val);
} else {
return array($val);
}
} else {
$pointer[$obj[0]] = mergecnf(array('config_name' => $obj[1], 'config_value' => $val));
}
$keys = explode($separator, $path);
return $pointer;
}//end mergecnf()
// walk the array creating keys if they don't exist
foreach ($keys as $key) {
$arr = &$arr[$key];
}
// assign the variable
$arr = $value;
}