Files
MoneyFlix/crm/Core/EnvironmentLoader.php
1sonhador 9d43854277 feat: Initial MoneyFlix project setup
- Created separate MoneyFlix project directory
- Copied Node.js redirector from production server
- Added CRM PHP code (Redirects module, Core classes, Config, Routes, Views)
- Created comprehensive documentation (README_MONEYFLIX.md)
- Added sync script to keep CRM code updated (sync-from-crm.sh)
- Configured .gitignore for Node.js and PHP
- Set up proper project structure for multi-client isolation

This separates MoneyFlix from the main CRM to avoid confusion
between different client systems and provides a dedicated
environment for MoneyFlix-specific development and maintenance.
2025-10-03 12:09:41 +01:00

322 lines
9.8 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Core;
/**
* Environment Loader
*
* Loads environment variables from config.env file into $_ENV superglobal.
* Ensures consistent environment configuration across web and CLI contexts.
*/
class EnvironmentLoader
{
private static bool $loaded = false;
private static array $config = [];
private static string $cacheFile = '';
private static int $lastModified = 0;
/**
* Load environment variables from config.env with caching
*/
public static function load(): void
{
$configFile = dirname(__DIR__, 2) . '/.env';
self::$cacheFile = dirname(__DIR__, 2) . '/storage/cache/env_cache.php';
if (!file_exists($configFile)) {
throw new \RuntimeException("Configuration file not found: {$configFile}");
}
$configModified = filemtime($configFile);
// Check if we can use cached version
if (self::$loaded && self::$lastModified === $configModified) {
return; // Already loaded and file hasn't changed
}
// Try to load from cache if it exists and is newer than config file
if (self::loadFromCache($configModified)) {
self::$loaded = true;
self::$lastModified = $configModified;
return;
}
// Parse config file and create cache
self::parseConfigFile($configFile);
self::saveToCache($configModified);
self::$loaded = true;
self::$lastModified = $configModified;
}
/**
* Get environment variable with optional default
*/
public static function get(string $key, $default = null)
{
self::load();
return $_ENV[$key] ?? $default;
}
/**
* Get all environment variables
*/
public static function all(): array
{
self::load();
return self::$config;
}
/**
* Check if environment variable exists
*/
public static function has(string $key): bool
{
self::load();
return isset($_ENV[$key]);
}
/**
* Get database configuration array
*/
public static function getDatabaseConfig(): array
{
self::load();
return [
'host' => $_ENV['DB_HOST'] ?? 'localhost',
'port' => $_ENV['DB_PORT'] ?? '3306',
'database' => $_ENV['DB_NAME'] ?? 'crm',
'username' => $_ENV['DB_USER'] ?? 'root',
'password' => $_ENV['DB_PASS'] ?? '',
'socket' => $_ENV['DB_SOCKET'] ?? null,
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
];
}
/**
* Reset loaded state (for testing)
*/
public static function reset(): void
{
self::$loaded = false;
self::$config = [];
}
/**
* Convert profile arrays to comma-separated string format
*/
private static function convertArrayToString(string $key, array $value): string
{
if ($key === 'DB_PROFILES') {
$profiles = [];
foreach ($value as $profileName => $profileConfig) {
$profiles[] = $profileName . ':' . $profileConfig;
}
return implode(',', $profiles);
}
// For other arrays, just join with commas
return implode(',', $value);
}
/**
* Get array configuration (for direct access to arrays)
*/
public static function getArray(string $key): array
{
self::load();
return self::$config[$key] ?? [];
}
/**
* Try to load configuration from cache
*/
private static function loadFromCache(int $configModified): bool
{
if (!file_exists(self::$cacheFile)) {
return false;
}
$cacheModified = filemtime(self::$cacheFile);
// Cache is older than config file
if ($cacheModified < $configModified) {
return false;
}
try {
$cached = include self::$cacheFile;
if (!is_array($cached) || !isset($cached['config']) || !isset($cached['timestamp'])) {
return false;
}
// Verify cache timestamp matches config file
if ($cached['timestamp'] !== $configModified) {
return false;
}
self::$config = $cached['config'];
// Load into $_ENV superglobal
self::loadIntoEnvironment();
return true;
} catch (\Exception $e) {
// Cache file is corrupted, ignore and reparse
return false;
}
}
/**
* Save configuration to cache
*/
private static function saveToCache(int $configModified): void
{
try {
// Ensure cache directory exists
$cacheDir = dirname(self::$cacheFile);
if (!is_dir($cacheDir)) {
mkdir($cacheDir, 0755, true);
}
$cacheContent = "<?php\n// Auto-generated environment cache - DO NOT EDIT\n";
$cacheContent .= "// Generated: " . date('Y-m-d H:i:s') . "\n";
$cacheContent .= "// Config file modified: " . date('Y-m-d H:i:s', $configModified) . "\n\n";
$cacheContent .= "return " . var_export([
'timestamp' => $configModified,
'config' => self::$config
], true) . ";\n";
file_put_contents(self::$cacheFile, $cacheContent, LOCK_EX);
} catch (\Exception $e) {
// Cache save failed, but don't break the application
// Just continue without cache
}
}
/**
* Parse the config file (extracted from original load method)
*/
private static function parseConfigFile(string $configFile): void
{
// Read and parse file manually to handle comments better
$lines = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
self::$config = [];
foreach ($lines as $line) {
$line = trim($line);
// Skip comments and empty lines
if (empty($line) || $line[0] === '#') {
continue;
}
// Parse key=value pairs
if (strpos($line, '=') !== false) {
[$key, $value] = explode('=', $line, 2);
$key = trim($key);
$value = trim($value);
// Remove quotes if present
if (in_array($value[0] ?? '', ['"', "'"])) {
$value = substr($value, 1, -1);
}
// Handle array syntax: KEY[index] = value
if (preg_match('/^([A-Z_]+)\[([^\]]+)\]$/', $key, $matches)) {
$arrayKey = $matches[1];
$index = $matches[2];
if (!isset(self::$config[$arrayKey])) {
self::$config[$arrayKey] = [];
}
self::$config[$arrayKey][$index] = $value;
} else {
self::$config[$key] = $value;
}
}
}
// Load into environment
self::loadIntoEnvironment();
}
/**
* Load configuration into $_ENV and $_SERVER
*/
private static function loadIntoEnvironment(): void
{
foreach (self::$config as $key => $value) {
if (is_array($value)) {
// Convert arrays to comma-separated string for backward compatibility
$_ENV[$key] = self::convertArrayToString($key, $value);
$_SERVER[$key] = $_ENV[$key];
// Also set individual array items as separate env vars
foreach ($value as $arrayKey => $arrayValue) {
$_ENV["{$key}_{$arrayKey}"] = $arrayValue;
$_SERVER["{$key}_{$arrayKey}"] = $arrayValue;
}
} else {
$_ENV[$key] = $value;
$_SERVER[$key] = $value;
}
}
}
/**
* Clear environment cache (useful for development)
*/
public static function clearCache(): bool
{
self::$cacheFile = self::$cacheFile ?: dirname(__DIR__, 2) . '/storage/cache/env_cache.php';
if (file_exists(self::$cacheFile)) {
return unlink(self::$cacheFile);
}
return true;
}
/**
* Get cache information for debugging
*/
public static function getCacheInfo(): array
{
$configFile = dirname(__DIR__, 2) . '/.env';
self::$cacheFile = self::$cacheFile ?: dirname(__DIR__, 2) . '/storage/cache/env_cache.php';
$info = [
'config_file' => $configFile,
'config_exists' => file_exists($configFile),
'config_modified' => file_exists($configFile) ? date('Y-m-d H:i:s', filemtime($configFile)) : null,
'cache_file' => self::$cacheFile,
'cache_exists' => file_exists(self::$cacheFile),
'cache_modified' => file_exists(self::$cacheFile) ? date('Y-m-d H:i:s', filemtime(self::$cacheFile)) : null,
'loaded' => self::$loaded,
'last_modified' => self::$lastModified,
'using_cache' => file_exists(self::$cacheFile) && file_exists($configFile) && filemtime(self::$cacheFile) >= filemtime($configFile)
];
return $info;
}
/**
* Force reload (bypass cache)
*/
public static function forceReload(): void
{
self::$loaded = false;
self::$lastModified = 0;
self::$config = [];
self::load();
}
}