fix: Fix environment variables not being captured correctly in PHP-FPM

- Fix priority order in loadSystemEnvironment() to check  and  first
- Add dynamic fallback in Environment::get() to handle variables set after initialization
- Ensure all environment variables are captured during bootstrap, including those set dynamically by PHP-FPM/FastCGI

Fixes issue where environment variables like RAPIDMAIL_USERNAME and RAPIDMAIL_PASSWORD were missing during bootstrap but available later in request processing.
This commit is contained in:
2025-11-02 21:11:29 +01:00
parent 6b633996a1
commit d2ee59bd65
2 changed files with 78 additions and 28 deletions

View File

@@ -23,7 +23,7 @@ final readonly class Environment
{
$key = $this->keyToString($key);
// 1. Check if direct env var exists
// 1. Check if direct env var exists in internal array
if (isset($this->variables[$key])) {
return $this->variables[$key];
}
@@ -34,10 +34,45 @@ final readonly class Environment
return $secretValue;
}
// 3. Return default
// 3. Fallback: Check system environment dynamically
// This handles cases where environment variables are set after Environment initialization
// (common in PHP-FPM where vars may be set during request processing)
$systemValue = $this->getFromSystemEnvironment($key);
if ($systemValue !== null) {
return $systemValue;
}
// 4. Return default
return $default;
}
/**
* Get variable from system environment as fallback
*
* This ensures we can access environment variables that were set
* after Environment initialization (e.g., by PHP-FPM/FastCGI)
*/
private function getFromSystemEnvironment(string $key): ?string
{
// Priority: $_ENV > $_SERVER > getenv()
// $_ENV and $_SERVER may contain dynamically set vars in PHP-FPM
if (isset($_ENV[$key]) && is_string($_ENV[$key])) {
return $_ENV[$key];
}
if (isset($_SERVER[$key]) && is_string($_SERVER[$key]) && !str_starts_with($key, 'HTTP_')) {
return $_SERVER[$key];
}
$value = getenv($key);
if ($value !== false && is_string($value)) {
return $value;
}
return null;
}
public function getRequired(EnvKey|string $key): mixed
{
$key = $this->keyToString($key);
@@ -115,11 +150,7 @@ final readonly class Environment
*/
public function all(): array
{
return array_merge(
#$_ENV,
#$_SERVER,
$this->variables
);
return $this->variables;
}
/**