Completed
Push — 6.0 ( 95a01d...4b0b4a )
by liu
02:23
created

Driver::append()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
declare (strict_types = 1);
12
13
namespace think\cache;
14
15
use Closure;
16
use DateInterval;
17
use DateTime;
18
use DateTimeInterface;
19
use Exception;
20
use Psr\SimpleCache\CacheInterface;
21
use think\Container;
22
use think\contract\CacheHandlerInterface;
23
use think\exception\InvalidArgumentException;
24
use throwable;
25
26
/**
27
 * 缓存基础类
28
 */
29
abstract class Driver implements CacheInterface, CacheHandlerInterface
30
{
31
    /**
32
     * 驱动句柄
33
     * @var object
34
     */
35
    protected $handler = null;
36
37
    /**
38
     * 缓存读取次数
39
     * @var integer
40
     */
41
    protected $readTimes = 0;
42
43
    /**
44
     * 缓存写入次数
45
     * @var integer
46
     */
47
    protected $writeTimes = 0;
48
49
    /**
50
     * 缓存参数
51
     * @var array
52
     */
53
    protected $options = [];
54
55
    /**
56
     * 缓存标签
57
     * @var array
58
     */
59
    protected $tag = [];
60
61
    /**
62
     * 获取有效期
63
     * @access protected
64
     * @param integer|DateTimeInterface|DateInterval $expire 有效期
65
     * @return int
66
     */
67 3
    protected function getExpireTime($expire): int
68
    {
69 3
        if ($expire instanceof DateTimeInterface) {
70
            $expire = $expire->getTimestamp() - time();
71 3
        } elseif ($expire instanceof DateInterval) {
72
            $expire = DateTime::createFromFormat('U', (string) time())
73
                ->add($expire)
74
                ->format('U') - time();
75
        }
76
77 3
        return (int) $expire;
78
    }
79
80
    /**
81
     * 获取实际的缓存标识
82
     * @access public
83
     * @param string $name 缓存名
84
     * @return string
85
     */
86
    public function getCacheKey(string $name): string
87
    {
88
        return $this->options['prefix'] . $name;
89
    }
90
91
    /**
92
     * 读取缓存并删除
93
     * @access public
94
     * @param string $name 缓存变量名
95
     * @return mixed
96
     */
97
    public function pull(string $name)
98
    {
99
        $result = $this->get($name, false);
100
101
        if ($result) {
102
            $this->delete($name);
103
            return $result;
104
        }
105
    }
106
107
    /**
108
     * 追加(数组)缓存
109
     * @access public
110
     * @param string $name  缓存变量名
111
     * @param mixed  $value 存储数据
112
     * @return void
113
     */
114 3
    public function push(string $name, $value): void
115
    {
116 3
        $item = $this->get($name, []);
117
118 3
        if (!is_array($item)) {
119
            throw new InvalidArgumentException('only array cache can be push');
120
        }
121
122 3
        $item[] = $value;
123
124 3
        if (count($item) > 1000) {
125
            array_shift($item);
126
        }
127
128 3
        $item = array_unique($item);
129
130 3
        $this->set($name, $item);
131 3
    }
132
133
    /**
134
     * 追加TagSet数据
135
     * @access public
136
     * @param string $name  缓存变量名
137
     * @param mixed  $value 存储数据
138
     * @return void
139
     */
140 3
    public function append(string $name, $value): void
141
    {
142 3
        $this->push($name, $value);
143 3
    }
144
145
    /**
146
     * 如果不存在则写入缓存
147
     * @access public
148
     * @param string $name   缓存变量名
149
     * @param mixed  $value  存储数据
150
     * @param int    $expire 有效时间 0为永久
151
     * @return mixed
152
     */
153
    public function remember(string $name, $value, $expire = null)
154
    {
155
        if ($this->has($name)) {
156
            return $this->get($name);
157
        }
158
159
        $time = time();
160
161
        while ($time + 5 > time() && $this->has($name . '_lock')) {
162
            // 存在锁定则等待
163
            usleep(200000);
164
        }
165
166
        try {
167
            // 锁定
168
            $this->set($name . '_lock', true);
169
170
            if ($value instanceof Closure) {
171
                // 获取缓存数据
172
                $value = Container::getInstance()->invokeFunction($value);
173
            }
174
175
            // 缓存数据
176
            $this->set($name, $value, $expire);
177
178
            // 解锁
179
            $this->delete($name . '_lock');
180
        } catch (Exception | throwable $e) {
181
            $this->delete($name . '_lock');
182
            throw $e;
183
        }
184
185
        return $value;
186
    }
187
188
    /**
189
     * 缓存标签
190
     * @access public
191
     * @param string|array $name 标签名
192
     * @return TagSet
193
     */
194 3
    public function tag($name): TagSet
195
    {
196 3
        $name = (array) $name;
197 3
        $key  = implode('-', $name);
198
199 3
        if (!isset($this->tag[$key])) {
200 3
            $this->tag[$key] = new TagSet($name, $this);
201
        }
202
203 3
        return $this->tag[$key];
204
    }
205
206
    /**
207
     * 获取标签包含的缓存标识
208
     * @access public
209
     * @param string $tag 标签标识
210
     * @return array
211
     */
212 3
    public function getTagItems(string $tag): array
213
    {
214 3
        $name = $this->getTagKey($tag);
215 3
        return $this->get($name, []);
216
    }
217
218
    /**
219
     * 获取实际标签名
220
     * @access public
221
     * @param string $tag 标签名
222
     * @return string
223
     */
224 3
    public function getTagKey(string $tag): string
225
    {
226 3
        return $this->options['tag_prefix'] . md5($tag);
227
    }
228
229
    /**
230
     * 序列化数据
231
     * @access protected
232
     * @param mixed $data 缓存数据
233
     * @return string
234
     */
235 3
    protected function serialize($data): string
236
    {
237 3
        if (is_numeric($data)) {
238 3
            return (string) $data;
239
        }
240
241 3
        $serialize = $this->options['serialize'][0] ?? "serialize";
242
243 3
        return $serialize($data);
244
    }
245
246
    /**
247
     * 反序列化数据
248
     * @access protected
249
     * @param string $data 缓存数据
250
     * @return mixed
251
     */
252 3
    protected function unserialize(string $data)
253
    {
254 3
        if (is_numeric($data)) {
255 3
            return $data;
256
        }
257
258 3
        $unserialize = $this->options['serialize'][1] ?? "unserialize";
259
260 3
        return $unserialize($data);
261
    }
262
263
    /**
264
     * 返回句柄对象,可执行其它高级方法
265
     *
266
     * @access public
267
     * @return object
268
     */
269
    public function handler()
270
    {
271
        return $this->handler;
272
    }
273
274
    /**
275
     * 返回缓存读取次数
276
     * @access public
277
     * @return int
278
     */
279
    public function getReadTimes(): int
280
    {
281
        return $this->readTimes;
282
    }
283
284
    /**
285
     * 返回缓存写入次数
286
     * @access public
287
     * @return int
288
     */
289
    public function getWriteTimes(): int
290
    {
291
        return $this->writeTimes;
292
    }
293
294
    /**
295
     * 读取缓存
296
     * @access public
297
     * @param iterable $keys    缓存变量名
298
     * @param mixed    $default 默认值
299
     * @return iterable
300
     * @throws InvalidArgumentException
301
     */
302 3
    public function getMultiple($keys, $default = null): iterable
303
    {
304 3
        $result = [];
305
306 3
        foreach ($keys as $key) {
307 3
            $result[$key] = $this->get($key, $default);
308
        }
309
310 3
        return $result;
311
    }
312
313
    /**
314
     * 写入缓存
315
     * @access public
316
     * @param iterable               $values 缓存数据
317
     * @param null|int|\DateInterval $ttl    有效时间 0为永久
318
     * @return bool
319
     */
320 3
    public function setMultiple($values, $ttl = null): bool
321
    {
322 3
        foreach ($values as $key => $val) {
323 3
            $result = $this->set($key, $val, $ttl);
324
325 3
            if (false === $result) {
326 1
                return false;
327
            }
328
        }
329
330 3
        return true;
331
    }
332
333
    /**
334
     * 删除缓存
335
     * @access public
336
     * @param iterable $keys 缓存变量名
337
     * @return bool
338
     * @throws InvalidArgumentException
339
     */
340 3
    public function deleteMultiple($keys): bool
341
    {
342 3
        foreach ($keys as $key) {
343 3
            $result = $this->delete($key);
344
345 3
            if (false === $result) {
346 1
                return false;
347
            }
348
        }
349
350 3
        return true;
351
    }
352
353
    public function __call($method, $args)
354
    {
355
        return call_user_func_array([$this->handler, $method], $args);
356
    }
357
}
358