Skip to content

Commit e660074

Browse files
committed
suporte ao redis para salvar a contagem de arquivos
1 parent 69bc864 commit e660074

File tree

5 files changed

+167
-19
lines changed

5 files changed

+167
-19
lines changed

Dockerfile

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,10 @@ RUN apt-get update && apt-get install -y \
99
git \
1010
htop \
1111
libzip-dev \
12+
libhiredis-dev \
1213
&& docker-php-ext-install zip opcache \
13-
&& docker-php-ext-enable opcache
14+
&& pecl install redis \
15+
&& docker-php-ext-enable redis opcache
1416

1517
# Copia a configuração do OPCache
1618
COPY opcache.ini /usr/local/etc/php/conf.d/opcache.ini

app/config.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,14 @@
2626
define('SITE_DESCRIPTION', isset($_ENV['SITE_DESCRIPTION']) ? $_ENV['SITE_DESCRIPTION'] : 'Chapéu de paywall é marreta!');
2727
define('SITE_URL', isset($_ENV['SITE_URL']) ? $_ENV['SITE_URL'] : 'https://' . $_SERVER['HTTP_HOST']);
2828
define('DNS_SERVERS', isset($_ENV['DNS_SERVERS']) ? $_ENV['DNS_SERVERS'] : '1.1.1.1, 8.8.8.8');
29-
define('CACHE_DIR', __DIR__ . '/cache');
3029
define('DISABLE_CACHE', isset($_ENV['DISABLE_CACHE']) ? filter_var($_ENV['DISABLE_CACHE'], FILTER_VALIDATE_BOOLEAN) : false);
3130
define('SELENIUM_HOST', isset($_ENV['SELENIUM_HOST']) ? $_ENV['SELENIUM_HOST'] : 'localhost:4444');
31+
define('CACHE_DIR', __DIR__ . '/cache');
32+
33+
// Configurações de Redis
34+
define('REDIS_HOST', isset($_ENV['REDIS_HOST']) ? $_ENV['REDIS_HOST'] : 'localhost');
35+
define('REDIS_PORT', isset($_ENV['REDIS_PORT']) ? $_ENV['REDIS_PORT'] : 6379);
36+
define('REDIS_PREFIX', isset($_ENV['REDIS_PREFIX']) ? $_ENV['REDIS_PREFIX'] : 'marreta:');
3237

3338
/**
3439
* Configurações de Cache S3

app/inc/Cache.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
use Inc\Cache\CacheStorageInterface;
44
use Inc\Cache\DiskStorage;
55
use Inc\Cache\S3Storage;
6+
use Inc\Cache\RedisStorage;
67

78
/**
89
* Classe responsável pelo gerenciamento de cache do sistema
@@ -19,13 +20,21 @@ class Cache
1920
*/
2021
private $storage;
2122

23+
/**
24+
* @var RedisStorage Instância do Redis para contagem de arquivos
25+
*/
26+
private $redisStorage;
27+
2228
/**
2329
* Construtor da classe
2430
*
2531
* Inicializa o storage apropriado baseado na configuração
2632
*/
2733
public function __construct()
2834
{
35+
// Inicializa o RedisStorage para contagem de arquivos
36+
$this->redisStorage = new RedisStorage(CACHE_DIR);
37+
2938
// Se S3 está configurado e ativo, usa S3Storage
3039
if (defined('S3_CACHE_ENABLED') && S3_CACHE_ENABLED === true) {
3140
$this->storage = new S3Storage([
@@ -43,6 +52,16 @@ public function __construct()
4352
}
4453
}
4554

55+
/**
56+
* Obtém a contagem de arquivos em cache
57+
*
58+
* @return int Número de arquivos em cache
59+
*/
60+
public function getCacheFileCount(): int
61+
{
62+
return $this->redisStorage->countCacheFiles();
63+
}
64+
4665
/**
4766
* Gera um ID único para uma URL
4867
*

app/inc/Cache/RedisStorage.php

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
<?php
2+
3+
namespace Inc\Cache;
4+
5+
class RedisStorage implements CacheStorageInterface
6+
{
7+
/**
8+
* @var \Redis|null Redis client instance
9+
*/
10+
private $redis;
11+
12+
/**
13+
* @var string Diretório de cache para contagem de arquivos
14+
*/
15+
private $cacheDir;
16+
17+
/**
18+
* Construtor da classe
19+
*
20+
* @param string $cacheDir Diretório base para armazenamento do cache
21+
*/
22+
public function __construct(string $cacheDir)
23+
{
24+
$this->cacheDir = $cacheDir;
25+
26+
// Tenta inicializar conexão Redis
27+
try {
28+
$this->redis = new \Redis();
29+
$this->redis->connect(REDIS_HOST, REDIS_PORT, 2.5);
30+
$this->redis->setOption(\Redis::OPT_PREFIX, REDIS_PREFIX);
31+
} catch (\Exception $e) {
32+
// Se falhar, define redis como null
33+
$this->redis = null;
34+
}
35+
}
36+
37+
/**
38+
* Conta o número de arquivos no diretório de cache
39+
*
40+
* @return int Número de arquivos no diretório de cache
41+
*/
42+
public function countCacheFiles(): int
43+
{
44+
// Chave para armazenar a contagem de arquivos no Redis
45+
$cacheCountKey = 'cache_file_count';
46+
47+
// Se Redis estiver disponível
48+
if ($this->redis !== null) {
49+
// Verifica se a chave existe e tem valor
50+
$cachedCount = $this->redis->get($cacheCountKey);
51+
if ($cachedCount !== false) {
52+
return (int)$cachedCount;
53+
}
54+
}
55+
56+
// Se Redis não estiver disponível ou chave vazia, conta os arquivos
57+
$fileCount = iterator_count(new \FilesystemIterator($this->cacheDir));
58+
59+
// Se Redis estiver disponível, salva a contagem
60+
if ($this->redis !== null) {
61+
$this->redis->set($cacheCountKey, $fileCount);
62+
}
63+
64+
return $fileCount;
65+
}
66+
67+
/**
68+
* Atualiza a contagem de arquivos no Redis
69+
*
70+
* @param int $count Número de arquivos
71+
*/
72+
public function updateCacheFileCount(int $count): void
73+
{
74+
if ($this->redis !== null) {
75+
$this->redis->set('cache_file_count', $count);
76+
}
77+
}
78+
79+
/**
80+
* {@inheritdoc}
81+
*/
82+
public function exists(string $id): bool
83+
{
84+
return $this->redis !== null ? $this->redis->exists($id) : false;
85+
}
86+
87+
/**
88+
* {@inheritdoc}
89+
*/
90+
public function get(string $id): ?string
91+
{
92+
if ($this->redis === null) {
93+
return null;
94+
}
95+
96+
$content = $this->redis->get($id);
97+
return $content === false ? null : $content;
98+
}
99+
100+
/**
101+
* {@inheritdoc}
102+
*/
103+
public function set(string $id, string $content): bool
104+
{
105+
// Se Redis não estiver disponível, retorna false
106+
if ($this->redis === null) {
107+
return false;
108+
}
109+
110+
// Ao salvar um novo arquivo, atualiza a contagem
111+
$result = $this->redis->set($id, $content);
112+
113+
if ($result) {
114+
// Incrementa a contagem de arquivos no Redis
115+
$currentCount = $this->redis->get('cache_file_count') ?: 0;
116+
$this->redis->set('cache_file_count', $currentCount + 1);
117+
}
118+
119+
return $result;
120+
}
121+
}

app/index.php

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
*/
1313

1414
require_once 'config.php';
15+
require_once 'inc/Cache.php';
1516

1617
// Inicialização de variáveis
1718
$message = '';
@@ -36,6 +37,10 @@
3637
$message_type = MESSAGES['INVALID_URL']['type'];
3738
}
3839
}
40+
41+
// Inicializa o cache para contagem
42+
$cache = new Cache();
43+
$cache_folder = $cache->getCacheFileCount();
3944
?>
4045
<!DOCTYPE html>
4146
<html lang="pt-BR">
@@ -56,22 +61,19 @@
5661
<body class="bg-gray-50 min-h-screen">
5762
<div class="container mx-auto px-4 py-8 max-w-4xl">
5863
<!-- Cabeçalho da página -->
59-
<div class="text-center mb-8">
60-
<h1 class="text-4xl font-bold text-gray-800 mb-4">
61-
<img src="assets/svg/marreta.svg" class="inline-block w-12 h-12 mb-2" alt="Marreta">
62-
<?php echo SITE_NAME; ?>
63-
</h1>
64-
<p class="text-gray-600 text-lg"><?php echo SITE_DESCRIPTION; ?></p>
65-
<p class="text-gray-600 text-lg">
66-
<span class="font-bold text-blue-600">
67-
<?php
68-
$cache_folder = iterator_count(new FilesystemIterator('cache/'));
69-
echo number_format($cache_folder, 0, ',', '.');
70-
?>
71-
</span>
72-
<span>paredes derrubadas!</span>
73-
</p>
74-
</div>
64+
<div class="text-center mb-8">
65+
<h1 class="text-4xl font-bold text-gray-800 mb-4">
66+
<img src="assets/svg/marreta.svg" class="inline-block w-12 h-12 mb-2" alt="Marreta">
67+
<?php echo SITE_NAME; ?>
68+
</h1>
69+
<p class="text-gray-600 text-lg"><?php echo SITE_DESCRIPTION; ?></p>
70+
<p class="text-gray-600 text-lg">
71+
<span class="font-bold text-blue-600">
72+
<?php echo number_format($cache_folder, 0, ',', '.'); ?>
73+
</span>
74+
<span>paredes derrubadas!</span>
75+
</p>
76+
</div>
7577

7678
<!-- Formulário principal de análise de URLs -->
7779
<div class="bg-white rounded-xl shadow-lg p-8 mb-8">
@@ -231,5 +233,4 @@ class="flex items-center p-4 rounded-lg border-2 border-gray-200 hover:border-gr
231233
?>
232234
</script>
233235
</body>
234-
235236
</html>

0 commit comments

Comments
 (0)