Files

55 lines
1.6 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Core;
class Config
{
private static array $settings = [];
public static function load(string $envFile): void
{
if (file_exists($envFile)) {
$lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
$line = trim($line);
if ($line === '' || str_starts_with($line, '#')) {
continue;
}
if (str_contains($line, '=')) {
[$key, $value] = explode('=', $line, 2);
$key = trim($key);
$value = trim($value);
// Remove quotes if present
if (
(str_starts_with($value, '"') && str_ends_with($value, '"')) ||
(str_starts_with($value, "'") && str_ends_with($value, "'"))
) {
$value = substr($value, 1, -1);
}
if (!array_key_exists($key, $_SERVER) && !array_key_exists($key, $_ENV)) {
putenv("{$key}={$value}");
$_ENV[$key] = $value;
$_SERVER[$key] = $value;
}
}
}
}
}
public static function get(string $key, mixed $default = null): mixed
{
return $_ENV[$key] ?? $_SERVER[$key] ?? getenv($key) ?: $default;
}
public static function set(string $key, mixed $value): void
{
$_ENV[$key] = $value;
$_SERVER[$key] = $value;
}
}