index/src/Cache/Valkey/ValkeyProvider.php
2024-04-10 22:23:34 +00:00

82 lines
2.4 KiB
PHP

<?php
// ValkeyProvider.php
// Created: 2024-04-10
// Updated: 2024-04-10
namespace Index\Cache\Valkey;
use InvalidArgumentException;
use Redis;
use RedisException;
use Index\Cache\ICacheProvider;
use Index\Net\{DnsEndPoint,IPEndPoint,UnixEndPoint};
/**
* Valkey provider implementation.
*/
class ValkeyProvider implements ICacheProvider {
private Redis $redis;
private bool $persist;
public function __construct(ValkeyProviderInfo $providerInfo) {
$this->persist = $providerInfo->isPersistent();
$this->redis = new Redis;
$this->redis->setOption(Redis::OPT_PREFIX, $providerInfo->getPrefix());
if($this->persist)
$this->redis->pconnect($providerInfo->getServerHost(), $providerInfo->getServerPort());
else
$this->redis->connect($providerInfo->getServerHost(), $providerInfo->getServerPort());
if($providerInfo->hasPassword()) {
if($providerInfo->hasUsername())
$this->redis->auth([$providerInfo->getUsername(), $providerInfo->getPassword()]);
else
$this->redis->auth($providerInfo->getPassword());
}
if($providerInfo->hasDatabaseNumber())
$this->redis->select($providerInfo->getDatabaseNumber());
}
public function get(string $key): mixed {
$result = $this->redis->get($key);
return $result === false ? null : $result;
}
public function set(string $key, mixed $value, int $ttl = 0): void {
if($ttl < 0)
throw new InvalidArgumentException('$ttl must be equal to or greater than 0.');
$this->redis->setEx($key, $ttl, $value);
}
public function delete(string $key): void {
$this->redis->unlink($key);
}
public function touch(string $key, int $ttl = 0): void {
if($ttl < 0)
throw new InvalidArgumentException('$ttl must be equal to or greater than 0.');
$this->redis->expire($key, $ttl);
}
public function increment(string $key, int $amount = 1): int {
return $this->redis->incrBy($key, $amount);
}
public function decrement(string $key, int $amount = 1): int {
return $this->redis->decrBy($key, $amount);
}
public function close(): void {
if(!$this->persist)
$this->redis->close();
}
public function __destruct() {
$this->close();
}
}