/
SimpleCache.php
130 lines (105 loc) · 2.9 KB
/
SimpleCache.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
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
119
120
121
122
123
124
125
126
127
128
129
130
<?php
namespace Cake\Cache;
use Psr\SimpleCache\CacheInterface;
use Psr\SimpleCache\InvalidArgumentException;
use Cake\Cache\CacheEngine;
class SimpleCache implements CacheInterface
{
/**
* @var \Cake\Cache\CacheEngine
*/
protected $engine;
public function __construct(CacheEngine $engine)
{
$this->engine = $engine;
}
public function get($key, $default = null)
{
$result = $engine->read($key);
return $result === false ? $default : $result;
}
public function set($key, $value, $ttl = null)
{
if ($ttl !== null) {
$duration = $this->engine->getConfig('duration');
$this->engine->setConfig('duration', $this->ttlToSeconds($ttl));
}
try {
$result = $this->engine->write($key, $value);
} finally {
if ($ttl !== null) {
$this->engine->setConfig('duration', $duration);
}
}
return $result;
}
public function delete($key)
{
return $this->engine->delete($key);
}
public function clear()
{
return $this->engine->clear(false);
}
public function getMultiple($keys, $default = null)
{
$keys = $this->getAsArray($keys);
$result = [];
foreach ($keys as $key) {
$value = $this->engine->get($key, $default);
}
return $result;
}
public function setMultiple($values, $ttl = null)
{
if ($ttl !== null) {
$duration = $this->engine->getConfig('duration');
$this->engine->setConfig('duration', $this->ttlToSeconds($ttl));
}
try {
$result = true;
foreach ($values as $key => $value) {
$result = $this->engine->set($key, $value) && $result;
}
} finally {
if ($ttl !== null) {
$this->engine->setConfig('duration', $duration);
}
}
return $result;
}
public function deleteMultiple($keys)
{
$keys = $this->getAsArray($keys);
$result = true;
foreach ($keys as $key) {
$result = $this->engine->delete($key) && $result;
}
return $result;
}
public function has($key)
{
return $this->get($key) === null ? false : true;
}
protected function getAsArray($keys)
{
if ($keys instanceof \Traversable) {
return iterator_to_array($keys);
}
if (is_array($keys)) {
return $keys;
}
throw new InvalidArgumentException('"$keys" must be an array or instanceof Traversable');
}
/**
* @param int|\DateInterval $ttl
* @return int seconds
*/
function ttlToSeconds($ttl)
{
if (is_int($ttl)) {
return $ttl;
}
return $ttl->days * 86400 + $ttl->h * 3600 + $ttl->i * 60 + $ttl->s;
}
}