Files

135 lines
5.5 KiB
PHP

<?php
/**
* Environment Variables Loader
* Безопасная загрузка переменных окружения из .env файла
*/
if (!class_exists('EnvLoader')) {
class EnvLoader {
private static $loaded = false;
private static $vars = [];
private static $envPath = null;
public static function load($path = null) {
// Проверяем, не загружены ли уже переменные
if (self::$loaded && !empty(self::$vars)) {
return self::$vars;
}
if ($path === null) {
$path = dirname(__DIR__) . '/.env';
}
self::$envPath = $path;
if (!file_exists($path)) {
throw new Exception('.env file not found at: ' . $path);
}
// Логируем загрузку для отладки (только один раз)
if (function_exists('file_put_contents') && !self::$loaded) {
file_put_contents(__DIR__ . '/../../logs/debug.log', '[' . date('Y-m-d H:i:s') . '] EnvLoader: Loading .env from ' . $path . ', file_exists=' . (file_exists($path) ? 'YES' : 'NO') . PHP_EOL, FILE_APPEND);
}
// Используем абсолютный путь
$absolutePath = realpath($path);
if ($absolutePath === false) {
$absolutePath = $path;
}
$content = file_get_contents($absolutePath);
if ($content === false) {
throw new Exception('Failed to read .env file: ' . $absolutePath);
}
$lines = explode("\n", $content);
// Логируем содержимое файла для отладки (только один раз)
if (function_exists('file_put_contents') && !self::$loaded) {
file_put_contents(__DIR__ . '/../../logs/debug.log', '[' . date('Y-m-d H:i:s') . '] EnvLoader: Absolute path: ' . $absolutePath . PHP_EOL, FILE_APPEND);
file_put_contents(__DIR__ . '/../../logs/debug.log', '[' . date('Y-m-d H:i:s') . '] EnvLoader: Content length: ' . strlen($content) . ' bytes' . PHP_EOL, FILE_APPEND);
file_put_contents(__DIR__ . '/../../logs/debug.log', '[' . date('Y-m-d H:i:s') . '] EnvLoader: First 200 chars: ' . substr($content, 0, 200) . PHP_EOL, FILE_APPEND);
}
// Логируем количество строк (только один раз)
if (function_exists('file_put_contents') && !self::$loaded) {
file_put_contents(__DIR__ . '/../../logs/debug.log', '[' . date('Y-m-d H:i:s') . '] EnvLoader: Found ' . count($lines) . ' lines in .env file' . PHP_EOL, FILE_APPEND);
}
$parsedCount = 0;
foreach ($lines as $lineNum => $line) {
// Пропускаем пустые строки
if (trim($line) === '') {
continue;
}
// Пропускаем комментарии
if (strpos(trim($line), '#') === 0) {
continue;
}
// Парсим KEY=VALUE
if (strpos($line, '=') !== false) {
list($key, $value) = explode('=', $line, 2);
$key = trim($key);
$value = trim($value);
// Убираем кавычки если есть
$value = trim($value, '"\'');
// Сохраняем в $_ENV и наш массив
$_ENV[$key] = $value;
self::$vars[$key] = $value;
$parsedCount++;
// Логируем первые несколько переменных для отладки (только один раз)
if ($parsedCount <= 3 && function_exists('file_put_contents') && !self::$loaded) {
file_put_contents(__DIR__ . '/../../logs/debug.log', '[' . date('Y-m-d H:i:s') . '] EnvLoader: Parsed ' . $key . '=' . $value . PHP_EOL, FILE_APPEND);
}
}
}
self::$loaded = true;
// Логируем успешную загрузку (только один раз)
if (function_exists('file_put_contents') && !self::$loaded) {
file_put_contents(__DIR__ . '/../../logs/debug.log', '[' . date('Y-m-d H:i:s') . '] EnvLoader: Loaded ' . count(self::$vars) . ' variables, S3_ACCESS_KEY=' . (self::$vars['S3_ACCESS_KEY'] ?? 'NOT_SET') . PHP_EOL, FILE_APPEND);
}
}
public static function get($key, $default = null) {
self::load();
return self::$vars[$key] ?? $_ENV[$key] ?? $default;
}
public static function getRequired($key) {
$value = self::get($key);
if ($value === null || $value === '') {
throw new Exception("Required environment variable '{$key}' is not set");
}
return $value;
}
public static function getBool($key, $default = false) {
$value = self::get($key);
if ($value === null) {
return $default;
}
return in_array(strtolower($value), ['true', '1', 'yes', 'on']);
}
public static function getInt($key, $default = 0) {
$value = self::get($key);
return $value !== null ? intval($value) : $default;
}
public static function isLoaded() {
return self::$loaded;
}
public static function getEnvPath() {
return self::$envPath;
}
}
}