Skip to content

Commit 7719bdf

Browse files
committed
Convert to array only redis and memcached env vars, fix #59
1 parent e5d58ad commit 7719bdf

File tree

2 files changed

+25
-18
lines changed

2 files changed

+25
-18
lines changed

src/Config.php

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -96,23 +96,7 @@ private static function getEnvConfig(array $config): array {
9696
* @param array<string, mixed> $array
9797
*/
9898
private static function envVarToArray(array &$array, string $var, string $value): void {
99-
$var = substr($var, 4);
100-
$keys = array_map(strtolower(...), explode('_', $var));
101-
102-
$current = &$array;
103-
104-
foreach ($keys as $i => $key) {
105-
if (count($keys) === 1) {
106-
break;
107-
}
108-
109-
if (isset($current[$key]) && is_array($current[$key])) {
110-
$current = &$current[$key];
111-
unset($keys[$i]);
112-
} else {
113-
break;
114-
}
115-
}
99+
$lower_var = strtolower(substr($var, 4));
116100

117101
if (json_validate($value)) {
118102
try {
@@ -122,7 +106,25 @@ private static function envVarToArray(array &$array, string $var, string $value)
122106
}
123107
}
124108

125-
$current[implode('_', $keys)] = $value;
109+
// Redis and Memcached variables: PCA_REDIS_1_HOST $config['redis'][1]['host']
110+
if (str_starts_with($lower_var, 'redis') || str_starts_with($lower_var, 'memcached')) {
111+
$keys = explode('_', $lower_var);
112+
$final_key = array_pop($keys);
113+
114+
$current = &$array;
115+
116+
foreach ($keys as $key) {
117+
if (!isset($current[$key]) || !is_array($current[$key])) {
118+
$current[$key] = [];
119+
}
120+
$current = &$current[$key];
121+
}
122+
123+
$current[$final_key] = $value;
124+
} else {
125+
// All other variables: PCA_AUTH_PASSWORD $config['auth_password']
126+
$array[$lower_var] = $value;
127+
}
126128
}
127129

128130
/**

tests/ConfigTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,11 +63,16 @@ public function testEnvOverride(): void {
6363
public function testEnvNested(): void {
6464
putenv('PCA_REDIS_0_HOST=127.0.0.1');
6565
putenv('PCA_REDIS_0_PORT=6379');
66+
putenv('PCA_REDIS_2_HOST=localhost');
67+
putenv('PCA_REDIS_2_PORT=6380');
6668

6769
$redis_config = Config::get('redis', []);
6870

6971
$this->assertSame('127.0.0.1', $redis_config[0]['host'] ?? null);
7072
$this->assertSame(6379, $redis_config[0]['port'] ?? null);
73+
74+
$this->assertSame('localhost', $redis_config[2]['host'] ?? null);
75+
$this->assertSame(6380, $redis_config[2]['port'] ?? null);
7176
}
7277

7378
public function testEnvCollisionWithScalar(): void {

0 commit comments

Comments
 (0)