forked from kevinohashi/php-riot-api
-
Notifications
You must be signed in to change notification settings - Fork 2
/
FileSystemCache.php
93 lines (75 loc) · 1.65 KB
/
FileSystemCache.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
<?php
require_once('CacheInterface.php');
class FileSystemCache implements CacheInterface {
/**
* @var string
*/
private $directory;
/**
* @param string $directory Caching directory
*/
public function __construct($directory)
{
$this->directory = trim($directory, '/\\') . '/';
if ( ! file_exists($this->directory))
mkdir($this->directory, 0777, true);
}
/**
* @param string $key Check if the cache contains data for the specified key
* @return bool
*/
public function has($key)
{
if ( ! file_exists($this->getPath($key)))
return false;
$entry = $this->load($key);
return !$this->expired($entry);
}
/**
* @param string $key Gets data for specified key
* @return string|null
*/
public function get($key)
{
$entry = $this->load($key);
$data = null;
if ( ! $this->expired($entry))
$data = $entry->data;
return $data;
}
/**
* @param string $key
* @param $data
* @param int $ttl Time for the data to live inside the cache
* @return mixed
*/
public function put($key, $data, $ttl = 0)
{
$this->store($key, $data, $ttl, time());
}
private function load($key)
{
return json_decode(file_get_contents($this->getPath($key)));
}
private function store($key, $data, $ttl, $createdAt)
{
$entry = array(
'createdAt' => $createdAt,
'ttl' => $ttl,
'data' => $data
);
file_put_contents($this->getPath($key), json_encode($entry));
}
private function getPath($key)
{
return $this->directory . $this->hash($key);
}
private function expired($entry)
{
return $entry === null || time() >= ($entry->createdAt + $entry->ttl);
}
private function hash($key)
{
return md5($key);
}
}