fix: bug
This commit is contained in:
@@ -1,14 +1,31 @@
|
||||
<?php
|
||||
|
||||
function redisClient(): Redis
|
||||
function redisClient(): ?Redis
|
||||
{
|
||||
static $redis = null;
|
||||
static $initialized = false;
|
||||
|
||||
if ($initialized) {
|
||||
return $redis;
|
||||
}
|
||||
|
||||
$initialized = true;
|
||||
|
||||
if (!class_exists('Redis')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($redis === null) {
|
||||
$config = require __DIR__ . '/../config/config.php';
|
||||
$redis = new Redis();
|
||||
try {
|
||||
if (!@$redis->connect($config['redis']['host'], $config['redis']['port'])) {
|
||||
throw new RuntimeException('Redis connection failed.');
|
||||
$redis = null;
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
$redis = null;
|
||||
}
|
||||
}
|
||||
|
||||
return $redis;
|
||||
}
|
||||
|
||||
@@ -21,12 +21,24 @@ class Paste
|
||||
if ($expire_time !== null) {
|
||||
$ttl = max(1, $expire_time - time());
|
||||
$redis = redisClient();
|
||||
if ($redis !== null) {
|
||||
try {
|
||||
$redis->setex("paste:{$id}", $ttl, json_encode([
|
||||
'encrypted_text' => $encrypted_text,
|
||||
'iv' => $iv,
|
||||
'password_hash' => $password_hash,
|
||||
]));
|
||||
return true;
|
||||
} catch (Throwable $e) {
|
||||
// Fall back to MySQL so expiring pastes still work without Redis.
|
||||
}
|
||||
}
|
||||
|
||||
$stmt = $this->pdo->prepare(
|
||||
'INSERT INTO pastes (id, encrypted_text, iv, expire_time, password_hash)
|
||||
VALUES (?, ?, ?, ?, ?)'
|
||||
);
|
||||
return $stmt->execute([$id, $encrypted_text, $iv, $expire_time, $password_hash]);
|
||||
}
|
||||
|
||||
$stmt = $this->pdo->prepare(
|
||||
@@ -39,8 +51,9 @@ class Paste
|
||||
public function get(string $id): array|false
|
||||
{
|
||||
$redis = redisClient();
|
||||
if ($redis !== null) {
|
||||
try {
|
||||
$raw = $redis->get("paste:{$id}");
|
||||
|
||||
if ($raw !== false) {
|
||||
$json = json_decode($raw, true);
|
||||
return [
|
||||
@@ -50,6 +63,10 @@ class Paste
|
||||
'expire_time' => time() + $redis->ttl("paste:{$id}"),
|
||||
];
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
// Ignore Redis failures and fall back to MySQL.
|
||||
}
|
||||
}
|
||||
|
||||
$stmt = $this->pdo->prepare('SELECT * FROM pastes WHERE id = ? LIMIT 1');
|
||||
$stmt->execute([$id]);
|
||||
|
||||
Reference in New Issue
Block a user