Skip to content

Commit

Permalink
refactor: set config from env. variable (#2084)
Browse files Browse the repository at this point in the history
  • Loading branch information
ArnaudLigny authored Dec 15, 2024
1 parent a78d3b7 commit 5706907
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 29 deletions.
4 changes: 0 additions & 4 deletions docs/4-Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -1011,7 +1011,3 @@ For example, the following command set the website’s `baseurl`:
```bash
export CECIL_BASEURL="https://example.com/"
```

:::important
Only existing configuration options can be overridden: you can’t create new configuration options with environment variables.
:::
29 changes: 7 additions & 22 deletions src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ public function __construct(?array $config = null)
public function import(array $config, $mode = self::MERGE): void
{
$this->data->import($config, $mode);
$this->setFromEnv();
$this->validate();
$this->override();
}

/**
Expand Down Expand Up @@ -540,30 +540,15 @@ public function isCacheDirIsAbsolute(): bool
}

/**
* Overrides configuration with environment variables.
* Set configuration from environment variables.
*/
private function override(): void
private function setFromEnv(): void
{
$data = $this->data;
$applyEnv = function ($array) use ($data) {
$iterator = new \RecursiveIteratorIterator(
new \RecursiveArrayIterator($array),
\RecursiveIteratorIterator::SELF_FIRST
);
$iterator->rewind();
while ($iterator->valid()) {
$path = [];
foreach (range(0, $iterator->getDepth()) as $depth) {
$path[] = $iterator->getSubIterator($depth)->key();
}
$sPath = implode('_', $path);
if ($getEnv = getenv('CECIL_' . strtoupper($sPath))) {
$data->set(str_replace('_', '.', strtolower($sPath)), $this->castSetValue($getEnv));
}
$iterator->next();
foreach (getenv() as $key => $value) {
if (str_starts_with($key, 'CECIL_')) {
$this->data->set(str_replace(['cecil_', '_'], ['', '.'], strtolower($key)), $this->castSetValue($value));
}
};
$applyEnv($data->export());
}
}

/**
Expand Down
4 changes: 2 additions & 2 deletions tests/IntegrationTests.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ public function tearDown(): void
public function testBuid()
{
putenv('CECIL_DEBUG=true');
putenv('CECIL_TITLE=Cecil');
putenv('CECIL_DESCRIPTION=Description (env. variable)');
putenv('CECIL_TITLE=Cecil (env)');
putenv('CECIL_DESCRIPTION=Description (env)');
echo "\n";
Builder::create(
require($this->config),
Expand Down
1 change: 0 additions & 1 deletion tests/fixtures/website/config.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
<?php

return [
'debug' => true,
'title' => 'Cecil test',
'taxonomies' => [
'tests' => 'disabled',
Expand Down

0 comments on commit 5706907

Please sign in to comment.