1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Basis; |
4
|
|
|
|
5
|
|
|
use Basis\Converter; |
6
|
|
|
use Carbon\Carbon; |
7
|
|
|
|
8
|
|
|
class Cache |
9
|
|
|
{ |
10
|
|
|
private $converter; |
11
|
|
|
|
12
|
39 |
|
public function __construct(Converter $converter) |
13
|
|
|
{ |
14
|
39 |
|
$this->converter = $converter; |
15
|
39 |
|
if (!is_dir('.cache')) { |
16
|
4 |
|
mkdir('.cache'); |
17
|
|
|
} |
18
|
39 |
|
} |
19
|
|
|
|
20
|
|
|
private $cache = []; |
21
|
|
|
|
22
|
39 |
|
public function exists($key) |
23
|
|
|
{ |
24
|
39 |
|
$filename = '.cache/'.$key; |
25
|
39 |
|
if (file_exists($filename)) { |
26
|
1 |
|
if (!array_key_exists($key, $this->cache)) { |
27
|
|
|
$this->cache[$key] = include $filename; |
28
|
|
|
} |
29
|
1 |
|
return $this->cache[$key]['expire'] > Carbon::now()->getTimestamp(); |
30
|
|
|
} |
31
|
39 |
|
} |
32
|
|
|
|
33
|
1 |
|
public function get($key) |
34
|
|
|
{ |
35
|
1 |
|
if ($this->exists($key)) { |
36
|
1 |
|
return $this->converter->toObject($this->cache[$key]); |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
1 |
|
public function set($key, $value) |
41
|
|
|
{ |
42
|
1 |
|
$filename = '.cache/'.$key; |
43
|
1 |
|
$data = $this->converter->toArray($value); |
44
|
1 |
|
$string = '<?php return '.var_export($data, true).';'; |
45
|
|
|
|
46
|
1 |
|
file_put_contents($filename, $string); |
47
|
1 |
|
$this->cache[$key] = $data; |
48
|
1 |
|
} |
49
|
|
|
|
50
|
39 |
|
public function wrap($key, $callback) |
51
|
|
|
{ |
52
|
39 |
|
$hash = md5(json_encode($key)); |
53
|
39 |
|
if ($this->exists($hash)) { |
54
|
1 |
|
return $this->get($hash); |
55
|
|
|
} |
56
|
39 |
|
$result = call_user_func($callback); |
57
|
39 |
|
$expire = null; |
58
|
39 |
|
if (is_array($result) && array_key_exists('expire', $result)) { |
59
|
|
|
$expire = $result['expire']; |
60
|
39 |
|
} elseif (is_object($result) && property_exists($result, 'expire')) { |
61
|
1 |
|
$expire = $result->expire; |
62
|
|
|
} |
63
|
39 |
|
if ($expire && $expire > Carbon::now()->getTimestamp()) { |
64
|
1 |
|
$this->set($hash, $result); |
65
|
|
|
} |
66
|
39 |
|
return $result; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|