-
Notifications
You must be signed in to change notification settings - Fork 196
/
FileCache.php
executable file
·340 lines (298 loc) · 7.63 KB
/
FileCache.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
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
<?php
/*
* This file is heavily inspired and use code from Composer(getcomposer.org),
* in particular Composer/Cache and Composer/Util/FileSystem from 1.0.0-alpha7
*
* The original code and this file are both released under MIT license.
*
* The copyright holders of the original code are:
* (c) Nils Adermann <[email protected]>
* Jordi Boggiano <[email protected]>
*/
namespace Terminus\Caches;
use Symfony\Component\Finder\Finder;
use Terminus\Config;
/**
* Reads/writes to a filesystem cache
*/
class FileCache {
/**
* @var string cache path
*/
protected $root;
/**
* @var bool
*/
protected $enabled = true;
/**
* @var int files time to live
*/
protected $ttl = 36000;
/**
* @var int max total size
*/
protected $maxSize;
/**
* @var string key allowed chars (regex class)
*/
protected $whitelist;
/**
* Object constructor. Sets properties.
*
* @param array $arg_options Elements as follow:
* string cache_dir The location of the cache
* int ttl The cache file's default expiry time
* int maxSize The max total cache size
* string whitelist A list of characters that are allowed in path
*/
public function __construct(array $arg_options = []) {
$default_options = [
'cache_dir' => Config::get('cache_dir'),
'ttl' => 832040,
'max_size' => 267914296,
'whitelist' => 'a-z0-9._-',
];
$options = array_merge($default_options, $arg_options);
$this->root = rtrim($options['cache_dir'], '/\\') . '/';
$this->ttl = (int)$options['ttl'];
$this->maxSize = (int)$options['max_size'];
$this->whitelist = $options['whitelist'];
if (!file_exists($this->root)) {
$this->enabled = false;
}
}
/**
* Clean cache based on time to live and max size
*
* @return bool True if cache clean succeeded
*/
public function clean() {
if (!$this->enabled) {
return false;
}
$ttl = $this->ttl;
$maxSize = $this->maxSize;
// unlink expired files
if ($ttl > 0) {
$expire = new \DateTime();
$expire->modify('-' . $ttl . ' seconds');
$finder = $this->getFinder()->date(
'before ' . $expire->format(Config::get('date_format'))
);
foreach ($finder as $file) {
unlink($file->getRealPath());
}
}
// unlink older files if max cache size is exceeded
if ($maxSize > 0) {
$files = array_reverse(
iterator_to_array(
$this->getFinder()->sortByAccessedTime()->getIterator()
)
);
$total = 0;
foreach ($files as $file) {
if ($total + $file->getSize() <= $maxSize) {
$total += $file->getSize();
} else {
unlink($file->getRealPath());
}
}
}
return true;
}
/**
* Flushes all caches
*
* @return void
*/
public function flush() {
$finder = $this->getFinder();
foreach ($finder as $file) {
unlink($file->getRealPath());
}
}
/**
* Reads retrieves data from cache
*
* @param string $key A cache key
* @param array $options Elements as follows:
* [bool] decode_array Argument 2 for json_decode
* [bool] ttl TTL for file read
* @return bool|string The file contents or false
*/
public function getData($key, array $options = []) {
$defaults = [
'decode_array' => false,
'ttl' => null,
];
$options = array_merge($defaults, $options);
try {
$contents = $this->read($key, $options['ttl']);
} catch (\Exception $e) {
return false;
}
$data = [];
if ($contents) {
$data = json_decode($contents, $options['decode_array']);
}
return $data;
}
/**
* Returns the cache root
*
* @return string
*/
public function getRoot() {
return $this->root;
}
/**
* Checks if a file is in cache and return its filename
*
* @param string $key Cache key
* @param int $ttl Time to live
* @return bool|string The filename or false
*/
public function has($key, $ttl = null) {
if (!$this->enabled) {
return false;
}
$filename = $this->filename($key);
if (!file_exists($filename)) {
return false;
}
// use ttl param or global ttl
if ($ttl === null) {
$ttl = $this->ttl;
} elseif ($this->ttl > 0) {
$ttl = min((int)$ttl, $this->ttl);
} else {
$ttl = (int)$ttl;
}
//
if ($ttl > 0 && filemtime($filename) + $ttl < time()) {
if ($this->ttl > 0 && $ttl >= $this->ttl) {
unlink($filename);
}
return false;
}
return $filename;
}
/**
* Returns whether cache is enabled
*
* @return bool
*/
public function isEnabled() {
return $this->enabled;
}
/**
* Saves data to the cache, JSON-encoded
*
* @param string $key A cache key
* @param mixed $data Data to save to cache
* @return bool True if write succeeded
*/
public function putData($key, $data) {
$json = json_encode($data);
$result = $this->write($key, $json);
return $result;
}
/**
* Remove file from cache
*
* @param string $key Cache key
* @return bool
*/
public function remove($key) {
if (!$this->enabled) {
return false;
}
$filename = $this->filename($key);
if (file_exists($filename)) {
$unlinking = unlink($filename);
return (boolean)$unlinking;
}
return false;
}
/**
* Filename from key
*
* @param string $key Key to validate
* @return string
*/
protected function filename($key) {
$filename = $this->root . $this->validateKey($key);
return $filename;
}
/**
* Get a Finder that iterates in cache root only the files
*
* @return Finder
*/
protected function getFinder() {
$finder = Finder::create()->in($this->root)->files();
return $finder;
}
/**
* Reads from the cache file
*
* @param string $key A cache key
* @param integer $ttl The time to live
* @return bool|string The file contents or false
*/
protected function read($key, $ttl = null) {
$filename = $this->has($key, $ttl);
$data = false;
if ($filename) {
$data = file_get_contents($filename);
}
return $data;
}
/**
* Validate cache key
*
* @param string $key A cache key
* @return string A relative filename
*/
protected function validateKey($key) {
$url_parts = parse_url($key);
if (! empty($url_parts['scheme'])) { // is url
$parts = array('misc');
$part_parts = array($url_parts['scheme'] . '-');
if (isset($url_parts['host'])) {
$part_parts[] = $url_parts['host'];
}
if (!empty($url_parts['port'])) {
$part_parts[] = '-' . $url_parts['port'];
}
$parts[] = implode('', $part_parts);
$part_parts = array(substr($url_parts['path'], 1));
if (!empty($url_parts['query'])) {
$part_parts[] = '-' . $url_parts['query'];
}
$parts[] = implode('', $part_parts);
} else {
$key = str_replace('\\', '/', $key);
$parts = explode('/', ltrim($key));
}
$parts = preg_replace("#[^{$this->whitelist}]#i", '-', $parts);
$parts_string = implode('/', $parts);
return $parts_string;
}
/**
* Writes to cache file
*
* @param string $key A cache key
* @param string $contents The file contents
* @return bool True if write was successful
*/
protected function write($key, $contents) {
$filename = Config::get('cache_dir') . "/$key";
$written = false;
if ($filename) {
$written = (file_put_contents($filename, $contents) && touch($filename));
}
return $written;
}
}