- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCache.php
More file actions
122 lines (95 loc) · 2.29 KB
/
Cache.php
File metadata and controls
122 lines (95 loc) · 2.29 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
<?php
namespace Mpdf;
use DirectoryIterator;
class Cache
{
private $basePath;
private $cleanupInterval;
public function __construct($basePath, $cleanupInterval = 3600)
{
if (!is_int($cleanupInterval) && false !== $cleanupInterval) {
throw new \Mpdf\MpdfException('Cache cleanup interval has to be an integer or false');
}
if (!$this->createBasePath($basePath)) {
throw new \Mpdf\MpdfException(sprintf('Temporary files directory "%s" is not writable', $basePath));
}
$this->basePath = $basePath;
$this->cleanupInterval = $cleanupInterval;
}
protected function createBasePath($basePath)
{
if (!file_exists($basePath)) {
if (!$this->createBasePath(dirname($basePath))) {
return false;
}
if (!$this->createDirectory($basePath)) {
return false;
}
}
if (!is_writable($basePath) || !is_dir($basePath)) {
return false;
}
return true;
}
protected function createDirectory($basePath)
{
if (!mkdir($basePath)) {
return false;
}
if (!chmod($basePath, 0777)) {
return false;
}
return true;
}
public function tempFilename($filename)
{
return $this->getFilePath($filename);
}
public function has($filename)
{
return file_exists($this->getFilePath($filename));
}
public function load($filename)
{
return file_get_contents($this->getFilePath($filename));
}
public function write($filename, $data)
{
$tempFile = tempnam($this->basePath, 'cache_tmp_');
file_put_contents($tempFile, $data);
$path = $this->getFilePath($filename);
rename($tempFile, $path);
return $path;
}
public function remove($filename)
{
return unlink($this->getFilePath($filename));
}
public function clearOld()
{
$iterator = new DirectoryIterator($this->basePath);
/** @var \DirectoryIterator $item */
foreach ($iterator as $item) {
if (!$item->isDot()
&& $item->isFile()
&& !$this->isDotFile($item)
&& $this->isOld($item)) {
unlink($item->getPathname());
}
}
}
private function getFilePath($filename)
{
return $this->basePath . '/' . $filename;
}
private function isOld(DirectoryIterator $item)
{
return $this->cleanupInterval
? $item->getMTime() + $this->cleanupInterval < time()
: false;
}
public function isDotFile(DirectoryIterator $item)
{
return substr($item->getFilename(), 0, 1) === '.';
}
}