banker/src/Driver/RedisDriver.php

156 lines
3.0 KiB
PHP

<?php declare(strict_types=1);
/**
* Banker
*
* A Caching library implementing psr/cache (PSR 6) and psr/simple-cache (PSR 16)
*
* PHP version 8+
*
* @package Banker
* @author Timothy J. Warren <tim@timshomepage.net>
* @copyright 2016 - 2023 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.1.0
* @link https://git.timshomepage.net/timw4mail/banker
*/
namespace Aviat\Banker\Driver;
use Aviat\Banker\Exception\CacheException;
use Predis\Client;
use DateInterval;
/**
* Redis cache backend
*/
class RedisDriver extends AbstractDriver {
/**
* The object encapsulating the connection to the Redis server
*
* @var Client
*/
protected Client $conn;
/**
* RedisDriver constructor.
*
* @codeCoverageIgnore
* @param array $config
* @param array $options - Predis library connection options
* @throws CacheException
*/
public function __construct(array $config = [], array $options = [])
{
if ( ! class_exists(Client::class))
{
throw new CacheException('The redis driver requires the predis/predis composer package to be installed.');
}
$this->conn = new Client($config, $options);
}
/**
* Disconnect from redis server
* @codeCoverageIgnore
*/
public function __destruct()
{
$this->conn->quit();
}
/**
* See if a key currently exists in the cache
*
* @param string $key
* @return bool
*/
public function exists(string $key): bool
{
return (bool) $this->conn->exists($key);
}
/**
* Get the value for the selected cache key
*
* @param string $key
* @return mixed
*/
public function get(string $key): mixed
{
$raw = $this->conn->get($key);
if ($raw === NULL)
{
return null;
}
return unserialize($raw);
}
/**
* Set a cached value
*
* @param string $key
* @param mixed $value
* @param DateInterval|int|null $expires
* @return bool
*/
public function set(string $key, mixed $value, DateInterval|int|null $expires = NULL): bool
{
$value = serialize($value);
$status = ($expires !== NULL)
? $this->conn->set($key, $value, 'EX', $expires)
: $this->conn->set($key, $value);
return (string)$status === 'OK';
}
/**
* Remove an item from the cache
*
* @param string $key
* @return boolean
*/
public function delete(string $key): bool
{
// This call returns the number of keys deleted
return $this->conn->del([$key]) === 1;
}
/**
* Remove multiple items from the cache
*
* @param string[] $keys
* @return boolean
*/
public function deleteMultiple(array $keys = []): bool
{
$this->validateKeys($keys);
$res = $this->conn->del(...array_values($keys));
return $res === count($keys);
}
/**
* Empty the cache
*
* @return boolean
*/
public function flush(): bool
{
return (bool) $this->conn->flushdb();
}
/**
* Set the expiration timestamp of a key
*
* @param string $key
* @param int $expires
* @return boolean
*/
public function expiresAt(string $key, int $expires): bool
{
return (bool) $this->conn->expireat($key, $expires);
}
}