-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileStore.php
More file actions
118 lines (102 loc) · 2.38 KB
/
FileStore.php
File metadata and controls
118 lines (102 loc) · 2.38 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
<?php
/**
* Saves cached values in the file.
*
* @package SugiPHP.Cache
* @author Plamen Popov <tzappa@gmail.com>
* @license http://opensource.org/licenses/mit-license.php (MIT License)
*/
namespace SugiPHP\Cache;
class FileStore implements StoreInterface
{
/**
* Path to directory where cache files will be saved.
*/
protected $path;
/**
* Creates a File store
*
* @param string
*/
public function __construct($path)
{
$this->path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
/**
* {@inheritdoc}
*/
public function add($key, $value, $ttl = 0)
{
if ($this->has($key)) {
return false;
}
return $this->set($key, $value, $ttl);
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = 0)
{
$file = $this->filename($key);
$expire = ($ttl) ? time() + $ttl : "9999999999";
// serializing is done mainly to distinguish type of the $value - string, number, etc.
$contents = $expire.serialize($value);
return (boolean) (@file_put_contents($file, $contents, LOCK_EX));
}
/**
* {@inheritdoc}
*/
public function get($key)
{
$file = $this->filename($key);
if (!is_file($file)) {
return null;
}
$contents = file_get_contents($file);
// check TTL
$expire = substr($contents, 0, 10);
if ($expire < time()) {
// if cache is expired delete cache file
$this->delete($key);
return null;
}
return unserialize(substr($contents, 10));
}
/**
* {@inheritdoc}
*/
public function has($key)
{
return (is_null($this->get($key))) ? false : true;
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
@unlink($this->filename($key));
}
/**
* {@inheritdoc}
*/
public function flush()
{
$files = glob($this->path."*.cache");
if ($files) {
foreach ($files as $file) {
@unlink($file);
}
}
}
/**
* Generates a filename based on the $key parameter
*
* @param string $key
*
* @return string
*/
protected function filename($key)
{
return $this->path.md5($key).".cache";
}
}