FileCache.php
13.9 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
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
<?php
namespace Hood\Cache;
use Hood\Core\Root;
use Yaf\Exception;
/**
* Description of cache
*
* @author 13011908
*/
class FileCache extends Root implements CacheInterface
{
const DEFAULT_EXPIRE = 3600;
protected static $default = 'file';
protected static $instances = array();
protected $_cache_dir;
protected $_tag = null;
private $section = 'file';
private $node = 'cache';
public function __construct($childNode = null, $node = 'cache', $cachePath = null)
{
if ($cachePath == null) {
$server = $this->getServerHost('cache');
$this->node = ($node == null ? 'cache' : $node);
$_pathList = $cachePath = $server->getServerConfig($this->section, $this->node);
if ($childNode == null && is_array($cachePath)) {
$cachePath = (sys_get_temp_dir() . 'cached' . DIRECTORY_SEPARATOR);
} else {
$cachePath = $_pathList[$childNode];
}
}
$this->initFileInfo($cachePath);
}
private function initFileInfo($directory)
{
try {
$this->_cache_dir = new \SplFileInfo($directory);
} // PHP < 5.3 exception handle
catch (ErrorException $e) {
$this->_cache_dir = $this->_make_directory($directory, 0777, TRUE);
} // PHP >= 5.3 exception handle
catch (UnexpectedValueException $e) {
$this->_cache_dir = $this->_make_directory($directory, 0777, TRUE);
}
// If the defined directory is a file, get outta here
if ($this->_cache_dir->isFile()) {
throw new Exception('Unable to create cache directory as a file already exists : ' . $this->_cache_dir->getRealPath());
}
if (!$this->_cache_dir->isDir()) {
$this->_cache_dir = $this->_make_directory($directory, 0777, TRUE);
}
// Check the read status of the directory
if (!$this->_cache_dir->isReadable()) {
throw new Exception('Unable to read from the cache directory ' . $this->_cache_dir->getRealPath());
}
// Check the write status of the directory
if (!$this->_cache_dir->isWritable()) {
throw new Exception('Unable to write to the cache directory ' . $this->_cache_dir->getRealPath());
}
}
public function add($key, $value, $minutes)
{
}
public function increment($key, $value = 1)
{
$tag = $this->_tag;
if ($get = $this->get($key)) {
if (preg_match('/^\d+$/', $get)) {
$value = intval($get) + $value;
} else {
return false;
}
}
if ($tag) {
$this->tag($tag);
}
return $this->set($key, $value);
}
public function decrement($key, $value = 1)
{
$tag = $this->_tag;
if ($get = $this->get($key)) {
if (preg_match('/^\d+$/', $get)) {
$value = intval($get) - $value;
} else {
return false;
}
}
if ($tag) {
$this->tag($tag);
}
return $this->set($key, $value);
}
public function tag($tagName = null)
{
if ($tagName) {
$this->_tag = md5($tagName);
return $this;
} elseif (!empty($this->_tag)) {
$tag = $this->_tag;
unset($this->_tag);
return $tag . DIRECTORY_SEPARATOR;
} else {
return '';
}
}
public static function instance($group = NULL)
{
// If there is no group supplied
if ($group === NULL) {
// Use the default setting
$group = self::$default;
}
if (isset(self::$instances[$group])) {
// Return the current group if initiated already
return self::$instances[$group];
}
// Create a new cache type instance
self::$instances[$group] = new self();
// Return the instance
return self::$instances[$group];
}
/**
* Retrieve a cached value entry by id.
*
* // Retrieve cache entry from file group
* $data = self::instance('file')->get('foo');
*
* // Retrieve cache entry from file group and return 'bar' if miss
* $data = self::instance('file')->get('foo', 'bar');
*
* @param string id of cache to entry
* @param string default value to return if cache miss
* @return mixed
* @throws Cache_Exception
*/
public function get($id, $default = NULL)
{
$filename = self::filename($this->_sanitize_id($id));
$directory = $this->_resolve_directory($filename);
// Wrap operations in try/catch to handle notices
try {
// Open file
$file = new \SplFileInfo($directory . $filename);
// If file does not exist
if (!$file->isFile()) {
// Return default value
return $default;
} else {
// Open the file and parse data
$created = $file->getMTime();
$data = $file->openFile();
$lifetime = $data->fgets();
// If we're at the EOF at this point, corrupted!
if ($data->eof()) {
return false;
throw new Exception(__METHOD__ . ' corrupted cache file!');
}
$cache = '';
while ($data->eof() === FALSE) {
$cache .= $data->fgets();
}
// Test the expiry
if (($created + (int)$lifetime) < time()) {
// Delete the file
$this->_delete_file($file, NULL, TRUE);
return $default;
} else {
return unserialize($cache);
}
}
} catch (ErrorException $e) {
// Handle ErrorException caused by failed unserialization
if ($e->getCode() === E_NOTICE) {
throw new Exception(__METHOD__ . ' failed to unserialize cached object with message : ' . $e->getMessage());
}
// Otherwise throw the exception
throw $e;
}
}
/**
* Set a value to cache with id and lifetime
*
* $data = 'bar';
*
* // Set 'bar' to 'foo' in file group, using default expiry
* self::instance('file')->set('foo', $data);
*
* // Set 'bar' to 'foo' in file group for 30 seconds
* self::instance('file')->set('foo', $data, 30);
*
* @param string id of cache entry
* @param string data to set to cache
* @param integer lifetime in seconds
* @return boolean
*/
public function set($id, $data, $lifetime = NULL)
{
$filename = self::filename($this->_sanitize_id($id));
$directory = $this->_resolve_directory($filename);
// If lifetime is NULL
if ($lifetime === NULL) {
// Set to the default expiry
$lifetime = self::DEFAULT_EXPIRE;
}
// Open directory
$dir = new \SplFileInfo($directory);
// If the directory path is not a directory
if (!$dir->isDir()) {
// Create the directory
if (!mkdir($directory, 0777, TRUE)) {
throw new Exception(__METHOD__ . ' unable to create directory : ' . $directory);
}
// chmod to solve potential umask issues
chmod($directory, 0777);
}
// Open file to inspect
$resouce = new \SplFileInfo($directory . $filename);
$file = $resouce->openFile('w');
try {
$data = $lifetime . "\n" . serialize($data);
$file->fwrite($data, strlen($data));
return (bool)$file->fflush();
} catch (ErrorException $e) {
// If serialize through an error exception
if ($e->getCode() === E_NOTICE) {
// Throw a caching error
throw new Exception(__METHOD__ . ' failed to serialize data for caching with message : ' . $e->getMessage());
}
// Else rethrow the error exception
throw $e;
}
}
protected static function filename($string)
{
return sha1($string) . '.cache';
}
/**
* Delete a cache entry based on id
*
* // Delete 'foo' entry from the file group
* self::instance('file')->delete('foo');
*
* @param string id to remove from cache
* @return boolean
*/
public function delete($id)
{
$filename = self::filename($this->_sanitize_id($id));
$directory = $this->_resolve_directory($filename);
return $this->_delete_file(new \SplFileInfo($directory . $filename), NULL, TRUE);
}
/**
* Delete all cache entries.
*
* Beware of using this method when
* using shared memory cache systems, as it will wipe every
* entry within the system for all clients.
*
* // Delete all cache entries in the file group
* self::instance('file')->delete_all();
*
* @return boolean
*/
public function delete_all()
{
return $this->_delete_file($this->_cache_dir, TRUE);
}
protected function _delete_file(\SplFileInfo $file, $retain_parent_directory = FALSE, $ignore_errors = FALSE, $only_expired = FALSE)
{
// Allow graceful error handling
try {
// If is file
if ($file->isFile()) {
try {
if ($only_expired === FALSE) {
// We want to delete the file
$delete = TRUE;
} // Otherwise...
else {
// Assess the file expiry to flag it for deletion
$json = $file->openFile('r')->current();
$data = json_decode($json);
$delete = $data->expiry < time();
}
// If the delete flag is set delete file
if ($delete === TRUE)
return @unlink($file->getRealPath());
else
return FALSE;
} catch (ErrorException $e) {
// Catch any delete file warnings
if ($e->getCode() === E_WARNING) {
throw new Exception(__METHOD__ . ' failed to delete file : ' . $file->getRealPath());
}
}
} // Else, is directory
elseif ($file->isDir()) {
// Create new DirectoryIterator
$files = new DirectoryIterator($file->getPathname());
// Iterate over each entry
while ($files->valid()) {
// Extract the entry name
$name = $files->getFilename();
// If the name is not a dot
if ($name != '.' AND $name != '..') {
// Create new file resource
$fp = new \SplFileInfo($files->getRealPath());
// Delete the file
$this->_delete_file($fp);
}
// Move the file pointer on
$files->next();
}
// If set to retain parent directory, return now
if ($retain_parent_directory) {
return TRUE;
}
try {
// Remove the files iterator
// (fixes Windows PHP which has permission issues with open iterators)
unset($files);
// Try to remove the parent directory
return rmdir($file->getRealPath());
} catch (ErrorException $e) {
// Catch any delete directory warnings
if ($e->getCode() === E_WARNING) {
throw new Exception(__METHOD__ . ' failed to delete directory : ' . $file->getRealPath());
}
throw $e;
}
} else {
// We get here if a file has already been deleted
return FALSE;
}
} // Catch all exceptions
catch (Exception $e) {
// If ignore_errors is on
if ($ignore_errors === TRUE) {
// Return
return FALSE;
}
// Throw exception
throw $e;
}
}
protected function _resolve_directory($filename)
{
return $this->_cache_dir->getRealPath() . DIRECTORY_SEPARATOR . $this->tag() . $filename[0] . $filename[1] . DIRECTORY_SEPARATOR;
}
protected function _sanitize_id($id)
{
// Change slashes and spaces to underscores
return str_replace(array('/', '\\', ' '), '_', $id);
}
/**
* Makes the cache directory if it doesn't exist. Simply a wrapper for
* `mkdir` to ensure DRY principles
*
* @see http://php.net/manual/en/function.mkdir.php
* @param string directory
* @param string mode
* @param string recursive
* @param string context
* @return \SplFileInfo
* @throws Cache_Exception
*/
protected function _make_directory($directory, $mode = 0777, $recursive = FALSE, $context = NULL)
{
if (!mkdir($directory, $mode, $recursive)) {
throw new Exception('Failed to create the defined cache directory : ' . $directory);
}
chmod($directory, $mode);
return new \SplFileInfo($directory);;
}
/**
* Garbage collection method that cleans any expired
* cache entries from the cache.
*
* @return void
*/
public function garbage_collect()
{
$this->_delete_file($this->_cache_dir, TRUE, FALSE, TRUE);
return;
}
}