cachePath = PathManager::getCachePath() . '/'; $this->defaultTtl = 3600; // 1 hora por padrão $this->enabled = true; $this->ensureCacheDirectory(); } private function getLogger(): Logger { if ($this->logger === null) { $this->logger = new Logger('debug'); // Usar nível debug para cache } return $this->logger; } /** * Obter valor do cache */ public function get(string $key): mixed { if (!$this->enabled) { $this->getLogger()->cache('get', $key, false, ['reason' => 'cache_disabled']); return null; } $filename = $this->getCacheFilename($key); if (!file_exists($filename)) { $this->getLogger()->cache('get', $key, false, ['reason' => 'file_not_found']); return null; } $data = file_get_contents($filename); if ($data === false) { $this->getLogger()->cache('get', $key, false, ['reason' => 'read_error']); return null; } $cached = json_decode($data, true); if ($cached === null) { $this->getLogger()->cache('get', $key, false, ['reason' => 'json_decode_error']); return null; } // Verificar se expirou if (time() > $cached['expires']) { $this->delete($key); $this->getLogger()->cache('get', $key, false, ['reason' => 'expired']); return null; } $this->getLogger()->cache('get', $key, true, ['size' => strlen($data)]); return $cached['value']; } /** * Guardar valor no cache */ public function set(string $key, mixed $value, ?int $ttl = null): bool { if (!$this->enabled) { $this->getLogger()->cache('set', $key, false, ['reason' => 'cache_disabled']); return false; } $ttl = $ttl ?? $this->defaultTtl; $filename = $this->getCacheFilename($key); $data = [ 'value' => $value, 'expires' => time() + $ttl, 'created' => time() ]; $jsonData = json_encode($data); $result = file_put_contents($filename, $jsonData); $success = $result !== false; $this->getLogger()->cache('set', $key, $success, [ 'ttl' => $ttl, 'size' => strlen($jsonData) ]); return $success; } /** * Eliminar valor do cache */ public function delete(string $key): bool { $filename = $this->getCacheFilename($key); if (file_exists($filename)) { $result = unlink($filename); $this->getLogger()->cache('delete', $key, $result); return $result; } $this->getLogger()->cache('delete', $key, true, ['reason' => 'file_not_found']); return true; } /** * Verificar se existe no cache */ public function has(string $key): bool { return $this->get($key) !== null; } /** * Limpar todo o cache */ public function clear(): bool { $files = glob($this->cachePath . '*.cache'); foreach ($files as $file) { if (is_file($file)) { unlink($file); } } return true; } /** * Limpar cache de analytics */ public function clearAnalytics(): bool { $files = glob($this->cachePath . '*analytics*'); foreach ($files as $file) { if (is_file($file)) { unlink($file); } } return true; } /** * Obter estatísticas do cache */ public function getStats(): array { $files = glob($this->cachePath . '*.cache'); $totalSize = 0; $expiredCount = 0; $validCount = 0; foreach ($files as $file) { $size = filesize($file); $totalSize += $size; $data = file_get_contents($file); $cached = json_decode($data, true); if ($cached && time() > $cached['expires']) { $expiredCount++; } else { $validCount++; } } return [ 'total_files' => count($files), 'valid_files' => $validCount, 'expired_files' => $expiredCount, 'total_size' => $this->formatBytes($totalSize), 'cache_path' => $this->cachePath ]; } /** * Limpar cache expirado */ public function gc(): int { $files = glob($this->cachePath . '*.cache'); $deletedCount = 0; foreach ($files as $file) { $data = file_get_contents($file); $cached = json_decode($data, true); if ($cached && time() > $cached['expires']) { if (unlink($file)) { $deletedCount++; } } } return $deletedCount; } /** * Ativar/desativar cache */ public function setEnabled(bool $enabled): void { $this->enabled = $enabled; } /** * Cache com callback (memoização) */ public function remember(string $key, callable $callback, ?int $ttl = null): mixed { $value = $this->get($key); if ($value !== null) { $this->getLogger()->cache('remember', $key, true, ['reason' => 'cache_hit']); return $value; } $this->getLogger()->cache('remember', $key, true, ['reason' => 'cache_miss']); $value = $callback(); $this->set($key, $value, $ttl); return $value; } /** * Cache para APIs */ public function rememberApi(string $endpoint, callable $callback, ?int $ttl = null): array { $key = 'api_' . md5($endpoint); return $this->remember($key, function() use ($callback) { try { $result = $callback(); return [ 'status' => 'success', 'data' => $result, 'cached_at' => time() ]; } catch (\Exception $e) { return [ 'status' => 'error', 'message' => $e->getMessage(), 'cached_at' => time() ]; } }, $ttl); } /** * Obter nome do ficheiro de cache */ private function getCacheFilename(string $key): string { $safeKey = preg_replace('/[^a-zA-Z0-9_-]/', '_', $key); return $this->cachePath . $safeKey . '.cache'; } /** * Garantir que o diretório de cache existe */ private function ensureCacheDirectory(): void { if (!is_dir($this->cachePath)) { mkdir($this->cachePath, 0755, true); } } /** * Formatar bytes para leitura humana */ private function formatBytes(int $bytes): string { $units = ['B', 'KB', 'MB', 'GB']; $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = min($pow, count($units) - 1); $bytes /= pow(1024, $pow); return round($bytes, 2) . ' ' . $units[$pow]; } }