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

76 lines
2 KiB
PHP

<?php
// ArrayCacheProvider.php
// Created: 2024-04-10
// Updated: 2024-04-10
namespace Index\Cache\ArrayCache;
use InvalidArgumentException;
use Index\Cache\ICacheProvider;
/**
* Represents a dummy cache provider.
*/
class ArrayCacheProvider implements ICacheProvider {
private array $items = [];
public function get(string $key): mixed {
if(!array_key_exists($key, $this->items))
return null;
$item = $this->items[$key];
if($item['ttl'] > 0 && $item['ttl'] <= time()) {
unset($this->items[$key]);
return null;
}
return unserialize($item['value']);
}
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->items[$key] = [
'value' => serialize($value),
'ttl' => $ttl < 1 ? 0 : time() + $ttl,
];
}
public function delete(string $key): void {
if(array_key_exists($key, $this->items))
unset($this->items[$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');
if(array_key_exists($key, $this->items))
$this->items[$key]['ttl'] = $ttl < 1 ? 0 : time() + $ttl;
}
public function increment(string $key, int $amount = 1): int {
$exists = array_key_exists($key, $this->items);
$value = $exists ? unserialize($this->items[$key]['value']) : 0;
$value += $amount;
$serialised = serialize($value);
if($exists)
$this->items[$key]['value'] = $serialised;
else
$this->items[$key] = [
'value' => $serialised,
'ttl' => 0,
];
return $value;
}
public function decrement(string $key, int $amount = 1): int {
return $this->increment($key, $amount * -1);
}
public function close(): void {}
}