-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathFileCache.php
97 lines (78 loc) · 1.79 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
<?php
namespace Milo\Github\Storages;
use Milo\Github;
/**
* Naive file cache implementation.
*
* @author Miloslav Hůla (https://github.com/milo)
*/
class FileCache extends Github\Sanity implements ICache
{
/** @var string */
private $dir;
/**
* @param string temporary directory
*
* @throws MissingDirectoryException
*/
public function __construct($tempDir)
{
if (!is_dir($tempDir)) {
throw new MissingDirectoryException("Directory '$tempDir' is missing.");
}
$dir = $tempDir . DIRECTORY_SEPARATOR . 'milo.github-api';
if (!is_dir($dir)) {
set_error_handler(function($severity, $message, $file, $line) use ($dir, & $valid) {
restore_error_handler();
if (!is_dir($dir)) {
throw new MissingDirectoryException("Cannot create '$dir' directory.", 0, new \ErrorException($message, 0, $severity, $file, $line));
}
});
mkdir($dir);
restore_error_handler();
}
$this->dir = $dir;
}
/**
* @param string
* @param mixed
* @return mixed stored value
*/
public function save($key, $value)
{
file_put_contents(
$this->filePath($key),
serialize($value),
LOCK_EX
);
return $value;
}
/**
* @param string
* @return mixed|NULL
*/
public function load($key)
{
$path = $this->filePath($key);
if (is_file($path) && ($fd = fopen($path, 'rb')) && flock($fd, LOCK_SH)) {
$cached = stream_get_contents($fd);
flock($fd, LOCK_UN);
fclose($fd);
$success = TRUE;
set_error_handler(function() use (& $success) { return $success = FALSE; }, E_NOTICE);
$cached = unserialize($cached);
restore_error_handler();
if ($success) {
return $cached;
}
}
}
/**
* @param string
* @return string
*/
private function filePath($key)
{
return $this->dir . DIRECTORY_SEPARATOR . sha1($key) . '.php';
}
}