forked from leftypol/leftypol
CacheDriver: moved to subdirectory
This commit is contained in:
parent
8ee471c868
commit
311a5477f8
8 changed files with 8 additions and 8 deletions
69
inc/Data/Driver/Cache/RedisCacheDriver.php
Normal file
69
inc/Data/Driver/Cache/RedisCacheDriver.php
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
<?php
|
||||
namespace Vichan\Data\Driver\Cache;
|
||||
|
||||
defined('TINYBOARD') or exit;
|
||||
|
||||
|
||||
class RedisCacheDriver implements CacheDriver {
|
||||
use CacheDriverTrait;
|
||||
|
||||
private string $prefix;
|
||||
private \Redis $inner;
|
||||
|
||||
public function __construct(string $prefix, string $host, ?int $port, ?string $password, int $database) {
|
||||
$this->inner = new \Redis();
|
||||
$maybe_unix = self::asUnixSocketPath($host);
|
||||
|
||||
if ($maybe_unix !== null) {
|
||||
$this->inner->connect($maybe_unix);
|
||||
} elseif ($port === null) {
|
||||
$this->inner->connect($host);
|
||||
} else {
|
||||
// IP + port.
|
||||
$this->inner->connect($host, $port);
|
||||
}
|
||||
if ($password) {
|
||||
$this->inner->auth($password);
|
||||
}
|
||||
if (!$this->inner->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_JSON)) {
|
||||
throw new \RuntimeException('Unable to configure Redis serializer');
|
||||
}
|
||||
if (!$this->inner->select($database)) {
|
||||
throw new \RuntimeException('Unable to connect to Redis database!');
|
||||
}
|
||||
|
||||
$this->prefix = $prefix;
|
||||
}
|
||||
|
||||
public function get(string $key): mixed {
|
||||
$ret = $this->inner->get($this->prefix . $key);
|
||||
if ($ret === false) {
|
||||
return null;
|
||||
}
|
||||
if ($ret === null) {
|
||||
return false;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
public function set(string $key, mixed $value, mixed $expires = false): void {
|
||||
$value = $value === false ? null : $value;
|
||||
if ($expires === false) {
|
||||
$this->inner->set($this->prefix . $key, $value);
|
||||
} else {
|
||||
$this->inner->setEx($this->prefix . $key, $expires, $value);
|
||||
}
|
||||
}
|
||||
|
||||
public function delete(string $key): void {
|
||||
$this->inner->del($this->prefix . $key);
|
||||
}
|
||||
|
||||
public function flush(): void {
|
||||
if (empty($this->prefix)) {
|
||||
$this->inner->flushDB();
|
||||
} else {
|
||||
$this->inner->unlink($this->inner->keys("{$this->prefix}*"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue