Added the ability to override configuration properties with environment variables using the format CONFIGLIB_<CONFIG_NAME>_<PROPERTY_NAME>
This commit is contained in:
parent
b26d818d6b
commit
544b9f2e1c
3 changed files with 44 additions and 0 deletions
|
@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
|
||||
This update introduces minor improvements
|
||||
|
||||
### Added
|
||||
- Added the ability to override configuration properties with environment variables using the format
|
||||
`CONFIGLIB_<CONFIG_NAME>_<PROPERTY_NAME>`
|
||||
|
||||
### Fixed
|
||||
- Corrected a few lines of code in regards to missing variable definitions
|
||||
|
||||
|
|
|
@ -360,6 +360,38 @@
|
|||
throw new RuntimeException('Unable to read configuration file', $e);
|
||||
}
|
||||
|
||||
$prefix = 'CONFIGLIB_' . strtoupper($this->name) . '_';
|
||||
|
||||
foreach (getenv() as $key => $value)
|
||||
{
|
||||
if (str_starts_with($key, $prefix))
|
||||
{
|
||||
// Remove the prefix and split the rest of the key into parts
|
||||
$path = explode('_', str_replace($prefix, '', $key));
|
||||
$current = &$this->configuration;
|
||||
|
||||
// Navigate to the parent of the value to set, except for the last part
|
||||
foreach ($path as $index => $key_value)
|
||||
{
|
||||
$key_value = strtolower($key_value); // Convert to lowercase if needed
|
||||
|
||||
if ($index < count($path) - 1)
|
||||
{
|
||||
if (!is_array($current) || !array_key_exists($key_value, $current))
|
||||
{
|
||||
$current[$key_value] = [];
|
||||
}
|
||||
$current = &$current[$key_value];
|
||||
}
|
||||
else
|
||||
{
|
||||
// Set the value for the last part of the path
|
||||
$current[$key_value] = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->modified = false;
|
||||
Log::debug('net.nosial.configlib', 'Loaded configuration file: ' . $this->path);
|
||||
}
|
||||
|
|
8
tests/load.php
Normal file
8
tests/load.php
Normal file
|
@ -0,0 +1,8 @@
|
|||
<?php
|
||||
|
||||
require 'ncc';
|
||||
import('net.nosial.configlib');
|
||||
|
||||
$config = new \ConfigLib\Configuration('test');
|
||||
|
||||
var_dump($config->getConfiguration());
|
Loading…
Add table
Reference in a new issue