EngineFiles.class.php
2.44 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
<?php
/**
* Created by PhpStorm.
* User: Администратор
* Date: 10.12.13
* Time: 12:02
*/
namespace Cpeople\Classes\Cache;
class EngineFiles implements Engine
{
private $path;
private $defaultTTL = 3600;
public function __construct($path, $defaultTTL = 3600)
{
$this->path = $path;
$this->defaultTTL = (int) $defaultTTL;
if (!file_exists($this->path))
{
@mkdir($this->path, 0777, true);
}
}
private function getFileName($cacheId)
{
$md5 = md5($cacheId);
return $this->path . DIRECTORY_SEPARATOR . substr($md5, 0, 2) . DIRECTORY_SEPARATOR . $md5 . '.txt';
}
public function valid($cacheId, $ttl = null)
{
$retval = true;
if (empty($ttl))
{
$ttl = $this->defaultTTL;
}
try
{
$file = $this->getFileName($cacheId);
if (!file_exists($file))
{
throw new CacheException('file does not exist');
}
if (time() - filemtime($file) > $ttl)
{
throw new CacheException('too old');
}
}
catch (CacheException $e)
{
$retval = false;
}
return $retval;
}
public function save($cacheId, $data)
{
$file = $this->getFileName($cacheId);
$dir = dirname($file);
if (!file_exists($dir))
{
mkdir($dir, 0777, true);
}
if (gettype($data) != 'string')
{
$data = serialize($data);
}
file_put_contents($file, $data);
chmod($file, 0666);
}
public function get($cacheId)
{
$retval = file_get_contents($this->getFileName($cacheId));
if (substr($retval, 0, 2) == 'a:')
{
$retval = unserialize($retval);
}
return $retval;
}
public function clear()
{
$objects = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($this->path),
\RecursiveIteratorIterator::SELF_FIRST
);
foreach($objects as $name => $object)
{
if ($object->isFile())
{
unlink($object->getRealPath());
}
}
}
public function clearByTag($tag)
{
}
}