功能需求
通过这个函数,获取环境配置JSON文件的配置内容。
并且,如果是有全局的,优先用全局,再子级,覆盖继承。
/**
* @param string $path
* @param null $default
* @return mixed|null
*/
function config($path = 'app', $default = null)
{
static $data = [];
$path = explode('.', $path);
$name = array_shift($path);
if (!empty($name) && !isset($data[$name])) {
$global = DIR_ROOT . '/config/' . $name . '.json';
$data[$name] = [];
if (file_exists($global)) {
$data[$name] = json_decode(file_get_contents($global), true);
}
$file = DIR_ROOT . '/config/' . RUN_ENV . '/' . $name . '.json';
if (file_exists($file)) {
$data[$name] = array_merge_recursive(json_decode(file_get_contents($file), true), $data[$name]);
}
}
if (empty($path)) {
$ret = $data[$name];
} elseif (isset($data[$name])) {
$ret = $data[$name];
$i = 0;
while (($p = current($path)) !== false) {
$i++;
if (isset($ret[$p])) {
$ret = $ret[$p];
} else {
$ret = $default;
break;
}
next($path);
if ($i > 10) break;
}
} else {
$ret = $default;
}
if (func_get_arg(0) == 'app.log.file') {
$ret = preg_replace_callback('#%([ymdhis]{1})#i', function ($m) {
return date($m[1]);
}, $ret);
$ret = DIR_ROOT . '/' . ltrim($ret, '/');
}
return $ret;
}