- First commit
This commit is contained in:
commit
a6ea7b9cce
3 files changed
+128
No files matched your search
@@ -0,0 +1,86 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user