diff --git a/CHANGELOG.md b/CHANGELOG.md index 2051963..e2556b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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__` + ### Fixed - Corrected a few lines of code in regards to missing variable definitions diff --git a/src/ConfigLib/Configuration.php b/src/ConfigLib/Configuration.php index cdf7f47..1b813f9 100644 --- a/src/ConfigLib/Configuration.php +++ b/src/ConfigLib/Configuration.php @@ -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); } diff --git a/tests/load.php b/tests/load.php new file mode 100644 index 0000000..b13f340 --- /dev/null +++ b/tests/load.php @@ -0,0 +1,8 @@ +getConfiguration()); \ No newline at end of file