LSconfig: add escape_key, explode_keys and implode_keys helper methods

Allow escaping dot in config variable key
This commit is contained in:
Benjamin Renard 2023-10-12 18:59:45 +02:00
parent e77a96066d
commit 9384d2e312
Signed by: bn8
GPG key ID: 3E2E1CE1907115BC

View file

@ -59,6 +59,57 @@ class LSconfig {
return false; return false;
} }
/**
* Explode configuration variable keys
* @param string $value The variable name to explode
* @return array<string> The exploded variable keys
*/
public static function explode_keys($value) {
$keys = [];
$key = "";
for($i=0; $i<strlen($value); $i++) {
switch($value[$i]) {
case '\\':
$key .= $value[$i+1];
$i++;
break;
case '.':
$keys[] = $key;
$key = "";
break;
default:
$key .= $value[$i];
}
}
$keys[] = $key;
return $keys;
}
/**
* Escape a variable name key
* @param string $value The variable name key to explode
* @return string The escaped variable name key
*/
public static function escape_key($value) {
return str_replace('.', '\\.', $value);
}
/**
* Implode configuration variable keys
* @param array<array<string>|string> $args Function arguments could be an array of key or a key
* to implode
* @return string The imploded configuration variable keys
*/
public static function implode_keys(...$args) {
$keys = [];
foreach ($args as $arg)
if (is_array($arg))
$keys = array_merge($keys, $arg);
else
$keys[] = $arg;
return implode('.', array_map(['LSconfig', 'escape_key'], $keys));
}
/** /**
* Get a specific configuration variable value * Get a specific configuration variable value
* *
@ -73,7 +124,7 @@ class LSconfig {
* @return mixed The configuration variable value * @return mixed The configuration variable value
**/ **/
public static function get($var, $default=null, $cast=null, $data=null) { public static function get($var, $default=null, $cast=null, $data=null) {
$vars = explode('.', $var); $vars = self :: explode_keys($var);
$value = $default; $value = $default;
if (is_array($vars)) { if (is_array($vars)) {
$value = (is_array($data)?$data:self :: $data); $value = (is_array($data)?$data:self :: $data);
@ -142,7 +193,7 @@ class LSconfig {
} }
else { else {
foreach ($subkeys as $subkey) { foreach ($subkeys as $subkey) {
$key = "$root_key.$subkey"; $key = self :: implode_keys(self :: explode_keys($root_key), $subkey);
$return[$key] = self :: get($key, $default, $cast, $data); $return[$key] = self :: get($key, $default, $cast, $data);
} }
} }
@ -163,7 +214,7 @@ class LSconfig {
* @return boolean True si tout s'est bien passé, False sinon * @return boolean True si tout s'est bien passé, False sinon
**/ **/
public static function set($var,$val) { public static function set($var,$val) {
$vars=explode('.',$var); $vars = self :: explode_keys($var);
if(is_array($vars)) { if(is_array($vars)) {
$code='self :: $data'; $code='self :: $data';
foreach ($vars as $v) { foreach ($vars as $v) {