-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathFileCache.php
More file actions
226 lines (179 loc) · 5.99 KB
/
FileCache.php
File metadata and controls
226 lines (179 loc) · 5.99 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
<?php
declare(strict_types=1);
namespace PhpSpellcheck\Cache;
use Psr\Cache\CacheItemInterface;
use Composer\Autoload\ClassLoader;
use PhpSpellcheck\Exception\RuntimeException;
use PhpSpellcheck\Exception\InvalidArgumentException;
final class FileCache implements FileCacheInterface
{
/**
* @var array<string, CacheItemInterface>
*/
private array $deferred = [];
/**
* $namespace - The namespace of the cache (e.g., 'Aspell' creates .phpspellcache.cache/Aspell/*)
* $defaultLifetime - The default lifetime in seconds for cached items (0 = never expires)
* $directory - Optional custom directory path for cache storage.
*/
public function __construct(
private readonly string $namespace = '@',
private readonly int $defaultLifetime = 0,
private ?string $directory = null,
) {
if ($directory === null) {
$directory = $this->getDefaultDirectory();
}
$this->validateNamespace();
$directory .= DIRECTORY_SEPARATOR . $namespace;
if (!is_dir($directory) && !@mkdir($directory, 0o777, true) && !is_dir($directory)) {
throw new RuntimeException(\sprintf('Directory "%s" could not be created', $directory));
}
$this->directory = $directory .= DIRECTORY_SEPARATOR;
}
public static function create(
string $namespace = '@',
int $defaultLifetime = 0,
?string $directory = null
): self {
return new self($namespace, $defaultLifetime, $directory);
}
public function getItem(string $key): CacheItemInterface
{
$this->validateKey($key);
$filepath = $this->getFilePath($key);
$item = new CacheItem($key);
if (!file_exists($filepath)) {
return $item;
}
$data = \PhpSpellcheck\file_get_contents($filepath);
if ($data === '') {
return $item;
}
$value = unserialize($data);
if (!\is_object($value)
|| !property_exists($value, 'data')
|| !property_exists($value, 'expiresAt')
) {
return $item;
}
if ($value->expiresAt !== 0
&& $value->expiresAt !== null
&& $value->expiresAt <= time()
) {
unlink($filepath);
return $item;
}
$item->set($value->data)->setIsHit(true);
if (\is_int($value->expiresAt) && $value->expiresAt > 0) {
$item->expiresAt(new \DateTime('@' . $value->expiresAt));
}
return $item;
}
/**
* @param array<string> $keys
*
* @return iterable<CacheItemInterface>
*/
public function getItems(array $keys = []): iterable
{
return array_map(fn ($key): CacheItemInterface => $this->getItem($key), $keys);
}
public function hasItem(string $key): bool
{
return $this->getItem($key)->isHit();
}
public function clear(): bool
{
$this->deferred = [];
$files = glob($this->directory.'*');
if ($files === false || empty($files)) {
return false;
}
$result = true;
foreach ($files as $file) {
$result = unlink($file) && $result;
}
return $result;
}
public function deleteItem(string $key): bool
{
$this->validateKey($key);
unset($this->deferred[$key]);
if (!file_exists($this->getFilePath($key))) {
return true;
}
return unlink($this->getFilePath($key));
}
public function deleteItems(array $keys): bool
{
$result = true;
foreach ($keys as $key) {
$result = $this->deleteItem($key) && $result;
}
return $result;
}
public function save(CacheItemInterface $item): bool
{
$this->validateKey($item->getKey());
if (!property_exists($item, 'expiry')) {
throw new InvalidArgumentException('CacheItem expiry property is required');
}
$expiresAt = match(true) {
$item->expiry instanceof \DateTimeInterface => $item->expiry->getTimestamp(),
$this->defaultLifetime > 0 => time() + $this->defaultLifetime,
default => null
};
$value = (object) [
'data' => $item->get(),
'expiresAt' => $expiresAt,
];
$serialized = serialize($value);
$filepath = $this->getFilePath($item->getKey());
try {
return (bool) \PhpSpellcheck\file_put_contents($filepath, $serialized, LOCK_EX);
} catch (\Exception $e) {
return false;
}
}
public function saveDeferred(CacheItemInterface $item): bool
{
$this->validateKey($item->getKey());
$this->deferred[$item->getKey()] = $item;
return true;
}
public function commit(): bool
{
$success = true;
foreach ($this->deferred as $item) {
$success = $this->save($item) && $success;
}
$this->deferred = [];
return $success;
}
public function getFilePath(string $key): string
{
return $this->directory . $key;
}
private function getDefaultDirectory(): string
{
return \dirname(array_keys(ClassLoader::getRegisteredLoaders())[0]).'/.phpspellcheck.cache';
}
private function validateNamespace(): void
{
if (\PhpSpellcheck\preg_match('#[^-+_.A-Za-z0-9]#', $this->namespace, $match) === 1) {
throw new InvalidArgumentException(\sprintf('Namespace contains "%s" but only characters in [-+_.A-Za-z0-9] are allowed.', $match[0]));
}
}
private function validateKey(string $key): void
{
if (\PhpSpellcheck\preg_match('/^[a-zA-Z0-9_\.]+$/', $key) === 0) {
throw new InvalidArgumentException(
\sprintf(
'Invalid cache key "%s". A cache key can only contain letters (a-z, A-Z), numbers (0-9), underscores (_), and periods (.).',
$key
)
);
}
}
}