rosavox/lib/alveolata/conf/functions.php

104 lines
2.1 KiB
PHP
Raw Normal View History

2025-05-23 07:33:29 +00:00
<?php
namespace alveolata\conf;
// require_once(DIR_ALVEOLATA . '/definitions.php');
require_once(DIR_ALVEOLATA . '/file/functions.php');
require_once(DIR_ALVEOLATA . '/json/functions.php');
require_once(DIR_ALVEOLATA . '/cache/functions.php');
/**
* @var \alveolata\cache\interface_cache
* @author Christian Fraß <frass@greenscale.de>
*/
class _state
{
public static $path = 'conf.json';
public static $cache_kind = 'memory';
public static $cache_parameters = [];
public static $cache_instance = null;
}
/**
* @author Christian Fraß <frass@greenscale.de>
*/
function set_cache(
string $kind,
array $parameters = []
) : void
{
_state::$cache_kind = $kind;
_state::$cache_parameters = $parameters;
}
/**
* @author Christian Fraß <frass@greenscale.de>
*/
function set_path(
string $path
) : void
{
_state::$path = $path;
}
/**
* @param string $path
* @param any [$fallback] value to return in case no conf entry was found for the given path
* @param boolean [$throw_exception] if true, do not return the fallback in case of a missing entry, but throw an exception
* @return mixed
* @throw \Exception
* @author Christian Fraß <frass@greenscale.de>
*/
function get(
string $path,
$fallback = null,
$throw_exception = false
)
{
// prepare cache
if (_state::$cache_instance === null) {
_state::$cache_instance = \alveolata\cache\make(_state::$cache_kind, _state::$cache_parameters);
}
// get raw data
$data = \alveolata\cache\get(
_state::$cache_instance,
'data',
function () {
$content = \alveolata\file\read(_state::$path);
$data = \alveolata\json\decode($content);
return $data;
}
);
// get specific piece of information
$steps = (($path === '') ? [] : explode('.', $path));
$value = $data;
foreach ($steps as $step) {
if (! array_key_exists($step, $value)) {
$report = \alveolata\report\make(
'conf entry not set',
[
'path' => $path,
'fallback' => $fallback,
]
);
if ($throw_exception) {
throw (\alveolata\report_as_exception($report));
}
else {
\alveolata\log\warning_($report);
return $fallback;
}
}
else {
$value = $value[$step];
}
}
return $value;
}
?>