64 lines
1.5 KiB
PHP
64 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace MingTsay\Akanyan;
|
|
|
|
use MingTsay\Akanyan\Discord\Me;
|
|
|
|
require_once __DIR__ . '/../env.php';
|
|
|
|
class Redis
|
|
{
|
|
public const PREFIX = 'akanyan:discord:me:';
|
|
public const TTL = 600; // 10 minutes
|
|
protected static ?\Redis $redis = null;
|
|
|
|
/**
|
|
* @throws \RedisException
|
|
*/
|
|
protected static function connect(): \Redis
|
|
{
|
|
if (static::$redis === null) {
|
|
static::$redis = new \Redis();
|
|
static::$redis->connect('127.0.0.1');
|
|
}
|
|
return static::$redis;
|
|
}
|
|
|
|
protected static function getKey(string $u): string
|
|
{
|
|
return static::PREFIX . md5($u);
|
|
}
|
|
|
|
public static function getCachedMe(string $u): ?Me
|
|
{
|
|
try {
|
|
$redis = static::connect();
|
|
return unserialize($redis->get(static::getKey($u))) ?: null;
|
|
} catch (\RedisException $e) {
|
|
trigger_error($e->getMessage());
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public static function cacheMe(string $u, ?Me $me): ?Me
|
|
{
|
|
try {
|
|
$redis = static::connect();
|
|
$redis->setEx(static::getKey($u), static::TTL, serialize($me));
|
|
return $me;
|
|
} catch (\RedisException $e) {
|
|
trigger_error($e->getMessage());
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public static function unsetMe(string $u): void
|
|
{
|
|
try {
|
|
$redis = static::connect();
|
|
$redis->unlink(static::getKey($u));
|
|
} catch (\RedisException $e) {
|
|
trigger_error($e->getMessage());
|
|
}
|
|
}
|
|
}
|