-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathcache.php
50 lines (36 loc) · 1.17 KB
/
cache.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
<?php
class Cache {
const CACHE_DIR = 'cache';
const CACHE_FILE_EXT = '.json';
public $cache_file;
public $expiration_time;
public $data;
public function __construct($id, $expiration_time) {
$path = realpath(dirname(__FILE__)) . '/' . self::CACHE_DIR . '/';
if (!file_exists($path)) {
mkdir($path);
}
$this->expiration_time = $expiration_time;
$this->cache_file = $path . $id . self::CACHE_FILE_EXT;
}
public function check() {
if (!file_exists($this->cache_file)) {
return false;
}
$content = file_get_contents($this->cache_file);
$data = json_decode($content, true);
$file_time = intval($data['time']);
$current_time = time();
$time_left = $file_time - $current_time;
if ($time_left > 0) {
unset($data['time']);
$this->data = $data;
return true;
}
return false;
}
public function save($data) {
$data['time'] = time() + $this->expiration_time;
file_put_contents($this->cache_file, json_encode($data, JSON_FORCE_OBJECT));
}
}