57 lines
1.5 KiB
PHP
57 lines
1.5 KiB
PHP
<?php
|
|
class Env
|
|
{
|
|
private static $variables = [];
|
|
private static $loaded = false;
|
|
|
|
public static function load($filePath)
|
|
{
|
|
if (self::$loaded) return;
|
|
|
|
if (!file_exists($filePath)) {
|
|
throw new Exception("Archivo .env no encontrado en: $filePath");
|
|
}
|
|
|
|
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
|
foreach ($lines as $line) {
|
|
$line = trim($line);
|
|
if (empty($line) || $line[0] === '#') continue;
|
|
|
|
list($name, $value) = array_pad(explode('=', $line, 2), 2, '');
|
|
self::$variables[trim($name)] = trim(str_replace(['[', ']'], '', $value));
|
|
}
|
|
|
|
self::$loaded = true;
|
|
}
|
|
|
|
public static function get($key, $default = null)
|
|
{
|
|
return self::$variables[$key] ?? $default;
|
|
}
|
|
|
|
public static function isProduction()
|
|
{
|
|
return self::get('APP_MODE') == 1; // Corregido: 1 = PRD
|
|
}
|
|
|
|
public static function getByEnvironment($baseKey)
|
|
{
|
|
$key = self::isProduction() ? $baseKey : 'DEV_' . $baseKey;
|
|
return self::get($key);
|
|
}
|
|
|
|
public static function required($key)
|
|
{
|
|
$value = self::get($key);
|
|
if ($value === null) {
|
|
throw new Exception("Variable de entorno requerida faltante: $key");
|
|
}
|
|
return $value;
|
|
}
|
|
}
|
|
|
|
if (!function_exists('env')) {
|
|
function env($key, $default = null) {
|
|
return Env::get($key, $default);
|
|
}
|
|
} |