110 lines
2.8 KiB
PHP
110 lines
2.8 KiB
PHP
<?php
|
|
namespace app\common\cache;
|
|
|
|
use Psr\SimpleCache\CacheInterface;
|
|
|
|
class SimpleFileCache implements CacheInterface
|
|
{
|
|
protected $path;
|
|
protected $prefix;
|
|
|
|
public function __construct($path = null, $prefix = 'spreadsheet_')
|
|
{
|
|
$this->path = $path ?? CACHE_PATH;
|
|
$this->prefix = $prefix;
|
|
|
|
if (!is_dir($this->path)) {
|
|
mkdir($this->path, 0777, true);
|
|
}
|
|
}
|
|
|
|
protected function getFilePath(string $key): string
|
|
{
|
|
return $this->path . DIRECTORY_SEPARATOR . $this->prefix . md5($key) . '.cache';
|
|
}
|
|
|
|
public function get($key, $default = null): mixed
|
|
{
|
|
$file = $this->getFilePath($key);
|
|
if (!file_exists($file)) {
|
|
return $default;
|
|
}
|
|
$content = file_get_contents($file);
|
|
$data = unserialize($content);
|
|
if ($data['expire'] !== 0 && $data['expire'] < time()) {
|
|
@unlink($file);
|
|
return $default;
|
|
}
|
|
return $data['value'];
|
|
}
|
|
|
|
public function set($key, $value, $ttl = null): bool
|
|
{
|
|
$file = $this->getFilePath($key);
|
|
$expire = $ttl instanceof \DateInterval ? (new \DateTime())->add($ttl)->getTimestamp() : ($ttl ? time() + $ttl : 0);
|
|
$data = [
|
|
'expire' => $expire,
|
|
'value' => $value,
|
|
];
|
|
return file_put_contents($file, serialize($data)) !== false;
|
|
}
|
|
|
|
public function delete($key): bool
|
|
{
|
|
$file = $this->getFilePath($key);
|
|
return file_exists($file) ? unlink($file) : true;
|
|
}
|
|
|
|
public function clear(): bool
|
|
{
|
|
$files = glob($this->path . '/' . $this->prefix . '*.cache');
|
|
foreach ($files as $file) {
|
|
unlink($file);
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public function getMultiple($keys, $default = null): iterable
|
|
{
|
|
$results = [];
|
|
foreach ($keys as $key) {
|
|
$results[$key] = $this->get($key, $default);
|
|
}
|
|
return $results;
|
|
}
|
|
|
|
public function setMultiple($values, $ttl = null): bool
|
|
{
|
|
$success = true;
|
|
foreach ($values as $key => $value) {
|
|
if (!$this->set($key, $value, $ttl)) {
|
|
$success = false;
|
|
}
|
|
}
|
|
return $success;
|
|
}
|
|
|
|
public function deleteMultiple($keys): bool
|
|
{
|
|
$success = true;
|
|
foreach ($keys as $key) {
|
|
if (!$this->delete($key)) {
|
|
$success = false;
|
|
}
|
|
}
|
|
return $success;
|
|
}
|
|
|
|
public function has($key): bool
|
|
{
|
|
$file = $this->getFilePath($key);
|
|
if (!file_exists($file)) return false;
|
|
$data = unserialize(file_get_contents($file));
|
|
if ($data['expire'] !== 0 && $data['expire'] < time()) {
|
|
@unlink($file);
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
}
|