This repository has been archived by the owner on Nov 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cache.class.php
executable file
·395 lines (365 loc) · 9.4 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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
<?php
/**
* Copyright (C) 2015
* @author capkokoon / kokoon@protonmail.ch
* based on logic by Christian Metz - MetzWeb Networks
* License: GPL v2 http://www.gnu.org/licenses/old-licenses/gpl-2.0.fr.html
*
* Cache class
* Usage : $cache = new \Cache(array('name' => , 'path' =>, 'extension' =>));
*/
class Cache
{
/**
* @var array
*/
protected $settings;
/**
* @var array
*/
protected $cache;
/**
* @var array
*/
protected $filenames;
/**
* Default constructor
*
* @param string|array [optional] $config
* @return void
*/
public function __construct($config = array())
{
if (!is_array($config)) {
$config = array('name' => (string) $config);
}
$this->settings = array_merge(self::getDefaultSettings(), $config);
$this->setCache($this->settings['name']);
$this->setCachePath($this->settings['path']);
$this->setCacheExtension($this->settings['extension']);
}
/**
* Return default settings
*
* @return array
*/
protected static function getDefaultSettings()
{
return array('name' => 'default',
'path' => 'cache/',
'extension' => '.cache');
}
/**
* Check whether data is associated with a key
*
* @param string $key
* @return boolean
*/
public function isCached($key)
{
if ($cachedData = $this->_loadCache()) {
if (isset($cachedData[$key])) {
if (!$this->_isExpired($cachedData[$key]['time'], $cachedData[$key]['expire'])) {
return true;
}
}
}
return false; // If cache file doesn't exist or cache is empty or key doesn't exist in array, key isn't cached
}
/**
* Store data in the cache
*
* @param string $key
* @param mixed $data
* @param mixed [optional] $expires / TTL of the data in seconds
* @return self
*/
public function store($key, $data, $expires = 0)
{
if (is_string($expires)) {
if (intval($expires) > 0) {
$expires = strtotime($expires, 0);
}
}
$new_data = array(
'time' => time(),
'expire' => (int) $expires,
'data' => serialize($data)
);
$cache = $this->_loadCache();
if (is_array($cache)) {
$cache[(string) $key] = $new_data;
} else {
$cache = array((string) $key => $new_data);
}
$this->_saveCache($cache);
return $this;
}
/**
* Retrieve cached data by key
*
* @param string $key
* @return mixed
*/
public function retrieve($key)
{
$key = (string) $key;
if ($cache = $this->_loadCache()) {
if (isset($cache[$key])) {
if (!$this->_isExpired($cache[$key]['time'], $cache[$key]['expire'])) {
return unserialize($cache[$key]['data']);
}
}
}
return null;
}
/**
* Retrieve all cached data
*
* @param boolean [optional] $meta
* @return array | null
*/
public function retrieveAll($raw = false)
{
if ($cache = $this->_loadCache()) {
if (!$raw) {
$results = array();
foreach ($cache as $key => $value) {
$results[$key] = unserialize($value['data']);
}
return $results;
} else {
return $cache;
}
}
return null;
}
/**
* Delete cached entry by its key
*
* @param string $key
* @return object
*/
public function delete($key)
{
$key = (string) $key;
if ($cache = $this->_loadCache()) {
if (isset($cache[$key])) {
unset($cache[$key]);
$this->_saveCache($cache);
return $this;
}
}
throw new \Exception("Error: delete() - Key '{$key}' not found.");
}
/**
* Erase all expired entries
*
* @return object
*/
public function deleteExpired()
{
$cache = $this->_loadCache();
if (is_array($cache)) {
$i = 0;
foreach ($cache as $key => $value) {
if ($this->_isExpired($value['time'], $value['expire'])) {
unset($cache[$key]);
++$i;
}
}
if ($i > 0) {
$this->_saveCache($cache);
}
}
return $this;
}
/**
* Flush all cached entries
* @return object
*/
public function flush()
{
$this->cache = null; // Purge cache
$this->_saveCache(array());
return $this;
}
/**
* Increment key
* @return object
*/
public function increment($key)
{
$key = (string) $key;
if ($cache = $this->_loadCache()) {
if (isset($cache[$key])) {
$tmp = unserialize($cache[$key]['data']);
if (is_numeric($tmp)) {
++$tmp;
$cache[$key]['data'] = serialize($tmp);
$this->_saveCache($cache);
return $this;
}
}
}
throw new \Exception("Error: increment() - Key '{$key}' not found.");
}
/**
* Decrement key
* @return object
*/
public function decrement($key)
{
$key = (string) $key;
if ($cache = $this->_loadCache()) {
if (isset($cache[$key])) {
$tmp = unserialize($cache[$key]['data']);
if (is_numeric($tmp)) {
--$tmp;
$cache[$key]['data'] = serialize($tmp);
$this->_saveCache($cache);
return $this;
}
}
}
throw new \Exception("Error: decrement() - Key '{$key}' not found.");
}
/**
* Load cache
* @return cache if existing or not null / null otherwise
*/
protected function _loadCache()
{
if (!is_null($this->cache))
return $this->cache;
if (file_exists($this->getCacheFile())) {
$this->cache = json_decode(file_get_contents($this->getCacheFile()), true);
return $this->cache;
}
return null;
}
/**
* Save cache file
* @param $dataArray
*/
protected function _saveCache(array $data)
{
$this->cache = $data; // Save new data in object to avoid useless I/O access
return file_put_contents($this->getCacheFile(), json_encode($data));
}
/**
* Check whether a timestamp is still in the duration
*
* @param integer $timestamp
* @param integer $expiration
* @return boolean
*/
protected function _isExpired($timestamp, $expiration)
{
if ($expiration !== 0) {
return (time() - $timestamp > $expiration);
}
return false;
}
/**
* Check if a writable cache directory exists and if not create a new one
*
* @return boolean
*/
protected function _checkCacheDir()
{
if (!is_dir($this->getCachePath()) && !mkdir($this->getCachePath(), 0775, true)) {
throw new \Exception('Unable to create cache directory ' . $this->getCachePath());
} elseif (!is_readable($this->getCachePath()) || !is_writable($this->getCachePath())) {
if (!chmod($this->getCachePath(), 0775)) {
throw new \Exception($this->getCachePath() . ' must be readable and writeable');
}
}
return true;
}
/**
* Getters and setters
*/
/**
* Get the cache directory path
*
* @return string
*/
public function getCacheFile()
{
if (!isset($this->filenames[$this->settings['name']])) {
if ($this->_checkCacheDir()) {
$filename = preg_replace('/[^0-9a-z\.\_\-]/i', '', strtolower($this->settings['name']));
$this->filenames[$this->settings['name']] = $this->settings['path'] . sha1($filename) . $this->settings['extension'];
}
}
return $this->filenames[$this->settings['name']];
}
/**
* Cache path Setter
*
* @param string $path
* @return object
*/
public function setCachePath($path)
{
$this->settings['path'] = $path;
}
/**
* Cache path Getter
*
* @return string
*/
public function getCachePath()
{
return $this->settings['path'];
}
/**
* Cache name Setter
*
* @param string $name
* @return object
*/
public function setCache($name)
{
$this->cache = null; // Purge cache as we change cache
$this->settings['name'] = $name;
}
/**
* Cache name Getter
*
* @return void
*/
public function getCache()
{
return $this->settings['path'];
}
/**
* Cache file extension Setter
*
* @param string $ext
* @return object
*/
public function setCacheExtension($ext)
{
$this->settings['extension']= $ext;
}
/**
* Cache file extension Getter
*
* @return string
*/
public function getCacheExtension()
{
return $this->settings['extension'];
}
/**
* Settings Getter
*
* @return array
*/
public function getSettings()
{
return $this->settings;
}
}