-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.class.php
101 lines (80 loc) · 2.14 KB
/
cache.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
namespace phpCache;
use RuntimeException;
/**
* @copyright MIT
* @author X-NicON /~https://github.com/X-NicON
* @since 0.2
*/
class Cache
{
private array $cache = [];
private string $path;
public function __construct($name = 'phpcache', $dir = null, $ext = '.cache')
{
$dir = $dir ?? sys_get_temp_dir();
if (!is_dir($dir) && !mkdir($dir, 0775, true)) {
throw new RuntimeException('Unable to create cache directory (' . $dir . ')');
}
if (!is_readable($dir) || !is_writable($dir)) {
if (!chmod($dir, 0775)) {
throw new RuntimeException('Cache directory must be readable and writable (' . $dir . ')');
}
}
$this->path = $dir . '/' . $name . $ext;
if (file_exists($this->path)) {
$file = file_get_contents($this->path);
if (!empty($file)) {
$this->cache = unserialize($file);
}
}
}
public function __destruct()
{
$this->saveStore();
}
public function set($key, $value, $ttl = 0)
{
if ($ttl > 0) {
$ttl += time();
}
$this->cache[$key] = [
'e' => $ttl,
'v' => $value
];
}
public function get($key, $default = false)
{
if ($this->has($key)) {
return $this->cache[$key]['v'];
}
return $default;
}
public function remove($key): bool
{
if (array_key_exists($key, $this->cache)) {
unset($this->cache[$key]);
return true;
}
return false;
}
public function has($key): bool
{
if (array_key_exists($key, $this->cache)) {
if ($this->cache[$key]['e'] === 0 || $this->cache[$key]['e'] > time()) {
return true;
}
unset($this->cache[$key]);
}
return false;
}
public function clean()
{
$this->cache = [];
return $this->saveStore();
}
private function saveStore(): bool
{
return (bool)file_put_contents($this->path, serialize($this->cache));
}
}