-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleCache.php
More file actions
92 lines (68 loc) · 2.12 KB
/
SimpleCache.php
File metadata and controls
92 lines (68 loc) · 2.12 KB
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
<?php
namespace Security;
class SimpleCache {
private $cacheDir;
public function __construct(string $cacheDir) {
$this->cacheDir = rtrim($cacheDir, '/') . '/';
if (!is_dir($this->cacheDir)) {
mkdir($this->cacheDir, 0755, true);
}
}
public function set(string $key, $value, int $ttl = 3600): bool {
$filename = $this->getFilename($key);
$data = [
'expires' => time() + $ttl,
'value' => $value
];
return file_put_contents($filename, serialize($data)) !== false;
}
public function get(string $key) {
$filename = $this->getFilename($key);
if (!file_exists($filename)) {
return null;
}
$data = unserialize(file_get_contents($filename));
if ($data === false) {
return null;
}
if (time() > $data['expires']) {
unlink($filename);
return null;
}
return $data['value'];
}
public function has(string $key): bool {
$filename = $this->getFilename($key);
if (!file_exists($filename)) {
return false;
}
$data = unserialize(file_get_contents($filename));
if ($data === false) {
return false;
}
if (time() > $data['expires']) {
unlink($filename);
return false;
}
return true;
}
public function delete(string $key): bool {
$filename = $this->getFilename($key);
if (file_exists($filename)) {
return unlink($filename);
}
return true;
}
public function clear(): bool {
$files = glob($this->cacheDir . '*');
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
}
}
return true;
}
private function getFilename(string $key): string {
return $this->cacheDir . md5($key) . '.cache';
}
}