87 lines
2.3 KiB
PHP
87 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace Kash;
|
|
|
|
use Psr\SimpleCache\CacheInterface;
|
|
|
|
class ApcuCache implements CacheInterface
|
|
{
|
|
const DEFAULT_NS_SEPARATOR = ':';
|
|
|
|
public function __construct(
|
|
protected string $namespace,
|
|
protected int $ttl,
|
|
) {}
|
|
|
|
public function get(string $key, mixed $default = null): mixed
|
|
{
|
|
$value = apcu_fetch($this->fullkey($key), $status);
|
|
|
|
return $status === true ? $value : $default;
|
|
}
|
|
|
|
public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool
|
|
{
|
|
return apcu_store($this->fullkey($key), $value, $this->handleTTL($ttl));
|
|
}
|
|
|
|
public function delete(string $key): bool
|
|
{
|
|
return apcu_delete($this->fullkey($key));
|
|
}
|
|
|
|
public function clear() : bool
|
|
{
|
|
return apcu_clear_cache();
|
|
}
|
|
|
|
public function getMultiple(iterable $keys, mixed $default = null): iterable
|
|
{
|
|
$nsKeys = $this->fullkey($keys);
|
|
|
|
$result = apcu_fetch($nsKeys);
|
|
|
|
return array_combine(array_map(fn($e) => substr($e, strlen($this->namespace) + strlen(static::DEFAULT_NS_SEPARATOR)), $nsKeys), $result) + array_fill_keys($keys, $default);
|
|
}
|
|
|
|
public function setMultiple(iterable $values, null|int|\DateInterval $ttl = null): bool
|
|
{
|
|
$list = array_combine(array_map( [$this, 'prependNamespace' ], array_keys($values), $values);
|
|
|
|
$result = apcu_store($list, $this->ttl($ttl));
|
|
|
|
return in_array($result, [ [], true ], true);
|
|
}
|
|
|
|
public function deleteMultiple(iterable $keys): bool
|
|
{
|
|
return apcu_delete($this->fullkey($keys)) === [];
|
|
}
|
|
|
|
public function has(string $key): bool
|
|
{
|
|
return apcu_exists($this->fullkey($key));
|
|
}
|
|
|
|
protected function handleTTL(null|int|\DateInterval $ttl) : int
|
|
{
|
|
if ($ttl instanceof \DateInterval) {
|
|
$ttl = (new \DateTime)->add($ttl)->getTimestamp() - (new \DateTime)->getTimestamp();
|
|
}
|
|
|
|
$ttl ??= $this->ttl;
|
|
|
|
return (int) $ttl;
|
|
}
|
|
|
|
protected function fullkey(string|array $key) : string|array
|
|
{
|
|
return is_array($key) ? array_map([ $this, 'prependNamespace' ], $key) : $this->prependNamespace($key);
|
|
}
|
|
|
|
protected function prependNamespace(string $key) : string
|
|
{
|
|
return $this->namespace . static::DEFAULT_NS_SEPARATOR . $key;
|
|
}
|
|
}
|