Files
MoneyFlix/crm/Core/Cache/RedisManager.php
T
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

287 lines
6.9 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Core\Cache;
use Redis;
use Exception;
/**
* Redis Cache Manager
* Gestor de cache Redis para o BitReport CRM
*/
class RedisManager
{
private ?Redis $redis = null;
private string $prefix;
private int $defaultTtl;
private bool $enabled;
public function __construct(
string $host = '127.0.0.1',
int $port = 6379,
string $password = '',
int $database = 0,
string $prefix = 'bitreport:',
int $defaultTtl = 3600
) {
$this->prefix = $prefix;
$this->defaultTtl = $defaultTtl;
$this->enabled = false;
try {
$this->redis = new Redis();
$this->redis->connect($host, $port);
if (!empty($password)) {
$this->redis->auth($password);
}
$this->redis->select($database);
$this->enabled = true;
} catch (Exception $e) {
// Redis não disponível, usar cache em memória
error_log("Redis não disponível: " . $e->getMessage());
}
}
/**
* Verificar se o Redis está disponível
*/
public function isEnabled(): bool
{
return $this->enabled && $this->redis !== null;
}
/**
* Obter valor do cache
*/
public function get(string $key)
{
if (!$this->isEnabled()) {
return null;
}
try {
$value = $this->redis->get($this->prefix . $key);
return $value !== false ? json_decode($value, true) : null;
} catch (Exception $e) {
error_log("Erro ao obter cache Redis: " . $e->getMessage());
return null;
}
}
/**
* Definir valor no cache
*/
public function set(string $key, $value, ?int $ttl = null): bool
{
if (!$this->isEnabled()) {
return false;
}
try {
$ttl = $ttl ?? $this->defaultTtl;
$serializedValue = json_encode($value);
if ($ttl > 0) {
return $this->redis->setex($this->prefix . $key, $ttl, $serializedValue);
} else {
return $this->redis->set($this->prefix . $key, $serializedValue);
}
} catch (Exception $e) {
error_log("Erro ao definir cache Redis: " . $e->getMessage());
return false;
}
}
/**
* Eliminar valor do cache
*/
public function delete(string $key): bool
{
if (!$this->isEnabled()) {
return false;
}
try {
return $this->redis->del($this->prefix . $key) > 0;
} catch (Exception $e) {
error_log("Erro ao eliminar cache Redis: " . $e->getMessage());
return false;
}
}
/**
* Verificar se a chave existe
*/
public function exists(string $key): bool
{
if (!$this->isEnabled()) {
return false;
}
try {
return $this->redis->exists($this->prefix . $key);
} catch (Exception $e) {
error_log("Erro ao verificar cache Redis: " . $e->getMessage());
return false;
}
}
/**
* Incrementar valor
*/
public function increment(string $key, int $value = 1): int
{
if (!$this->isEnabled()) {
return 0;
}
try {
return $this->redis->incrBy($this->prefix . $key, $value);
} catch (Exception $e) {
error_log("Erro ao incrementar cache Redis: " . $e->getMessage());
return 0;
}
}
/**
* Decrementar valor
*/
public function decrement(string $key, int $value = 1): int
{
if (!$this->isEnabled()) {
return 0;
}
try {
return $this->redis->decrBy($this->prefix . $key, $value);
} catch (Exception $e) {
error_log("Erro ao decrementar cache Redis: " . $e->getMessage());
return 0;
}
}
/**
* Definir tempo de expiração
*/
public function expire(string $key, int $ttl): bool
{
if (!$this->isEnabled()) {
return false;
}
try {
return $this->redis->expire($this->prefix . $key, $ttl);
} catch (Exception $e) {
error_log("Erro ao definir expiração Redis: " . $e->getMessage());
return false;
}
}
/**
* Obter tempo restante de expiração
*/
public function ttl(string $key): int
{
if (!$this->isEnabled()) {
return -1;
}
try {
return $this->redis->ttl($this->prefix . $key);
} catch (Exception $e) {
error_log("Erro ao obter TTL Redis: " . $e->getMessage());
return -1;
}
}
/**
* Eliminar todas as chaves com prefixo
*/
public function clear(string $pattern = '*'): bool
{
if (!$this->isEnabled()) {
return false;
}
try {
$keys = $this->redis->keys($this->prefix . $pattern);
if (!empty($keys)) {
return $this->redis->del($keys) > 0;
}
return true;
} catch (Exception $e) {
error_log("Erro ao limpar cache Redis: " . $e->getMessage());
return false;
}
}
/**
* Obter estatísticas do Redis
*/
public function getStats(): array
{
if (!$this->isEnabled()) {
return [
'enabled' => false,
'connected' => false,
'keys' => 0,
'memory' => 0
];
}
try {
$info = $this->redis->info();
$keys = $this->redis->dbSize();
return [
'enabled' => true,
'connected' => true,
'keys' => $keys,
'memory' => $info['used_memory_human'] ?? '0B',
'version' => $info['redis_version'] ?? 'unknown',
'uptime' => $info['uptime_in_seconds'] ?? 0
];
} catch (Exception $e) {
return [
'enabled' => true,
'connected' => false,
'error' => $e->getMessage()
];
}
}
/**
* Obter instância Redis (para operações avançadas)
*/
public function getRedis(): ?Redis
{
return $this->redis;
}
/**
* Fechar conexão
*/
public function close(): void
{
if ($this->redis !== null) {
try {
$this->redis->close();
} catch (Exception $e) {
error_log("Erro ao fechar conexão Redis: " . $e->getMessage());
}
$this->redis = null;
$this->enabled = false;
}
}
/**
* Destructor
*/
public function __destruct()
{
$this->close();
}
}