Files

79 lines
2.8 KiB
PHP

<?php
namespace App\Core;
/**
* Core Redis Client for managing connections.
* Handles Sessions, Rate Limiting, OTP, and Caching.
*/
class RedisClient
{
private static ?\Redis $instance = null;
/**
* Get the singleton Redis connection instance
*/
public static function getInstance(): \Redis
{
if (self::$instance === null) {
$host = getenv('REDIS_HOST');
$port = getenv('REDIS_PORT');
$password = getenv('REDIS_PASSWORD');
$missing = [];
if ($host === false || $host === '') $missing[] = 'REDIS_HOST';
if ($port === false || $port === '') $missing[] = 'REDIS_PORT';
if (!empty($missing)) {
throw new \RuntimeException("Redis Configuration Error: Missing environment variable(s): " . implode(', ', $missing));
}
try {
$redis = new \Redis();
// Connect with a 2.5 second timeout
if (!$redis->connect($host, (int)$port, 2.5)) {
throw new \RuntimeException("Could not connect to Redis server at {$host}:{$port}");
}
// Authenticate ONLY if a non-empty password is provided in environment
if (!empty($password)) {
try {
if (!$redis->auth($password)) {
throw new \RuntimeException("Redis authentication failed with provided REDIS_PASSWORD.");
}
} catch (\RedisException $authEx) {
// If server does not have a password configured, catch and report clearly
if (str_contains($authEx->getMessage(), 'no password is set') || str_contains($authEx->getMessage(), 'without any password')) {
error_log("⚠️ [Redis Notice] REDIS_PASSWORD was provided in .env, but Redis server on {$host}:{$port} is configured without password.");
} else {
throw $authEx;
}
}
}
// Set prefix for Saqel to avoid collisions
$redis->setOption(\Redis::OPT_PREFIX, 'saqel:');
self::$instance = $redis;
} catch (\Exception $e) {
error_log("Redis Connection Error: " . $e->getMessage());
throw new \RuntimeException("Redis connection failed ({$host}:{$port}): " . $e->getMessage());
}
}
return self::$instance;
}
/**
* Helper to close the connection explicitly
*/
public static function close(): void
{
if (self::$instance !== null) {
self::$instance->close();
self::$instance = null;
}
}
}