Passed
Push — 6.0 ( 68a474...c911bb )
by liu
37:37 queued 22:25
created

Driver::remember()   B

Complexity

Conditions 7
Paths 33

Size

Total Lines 35
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 7
eloc 16
c 3
b 0
f 0
nc 33
nop 3
dl 0
loc 35
ccs 0
cts 15
cp 0
crap 56
rs 8.8333
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2021 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
            if (($hit = $this->get($name)) !== null) {
157
                return $hit;
158
            }
159
        }
160
161
        $time = time();
162
163
        while ($time + 5 > time() && $this->has($name . '_lock')) {
164
            // 存在锁定则等待
165
            usleep(200000);
166
        }
167
168
        try {
169
            // 锁定
170
            $this->set($name . '_lock', true);
171
172
            if ($value instanceof Closure) {
173
                // 获取缓存数据
174
                $value = Container::getInstance()->invokeFunction($value);
175
            }
176
177
            // 缓存数据
178
            $this->set($name, $value, $expire);
179
180
            // 解锁
181
            $this->delete($name . '_lock');
182
        } catch (Exception | throwable $e) {
183
            $this->delete($name . '_lock');
184
            throw $e;
185
        }
186
187
        return $value;
188
    }
189
190
    /**
191
     * 缓存标签
192
     * @access public
193
     * @param string|array $name 标签名
194 3
     * @return TagSet
195
     */
196 3
    public function tag($name): TagSet
197 3
    {
198
        $name = (array) $name;
199 3
        $key  = implode('-', $name);
200 3
201
        if (!isset($this->tag[$key])) {
202
            $this->tag[$key] = new TagSet($name, $this);
203 3
        }
204
205
        return $this->tag[$key];
206
    }
207
208
    /**
209
     * 获取标签包含的缓存标识
210
     * @access public
211
     * @param string $tag 标签标识
212 3
     * @return array
213
     */
214 3
    public function getTagItems(string $tag): array
215 3
    {
216
        $name = $this->getTagKey($tag);
217
        return $this->get($name, []);
218
    }
219
220
    /**
221
     * 获取实际标签名
222
     * @access public
223
     * @param string $tag 标签名
224 3
     * @return string
225
     */
226 3
    public function getTagKey(string $tag): string
227
    {
228
        return $this->options['tag_prefix'] . md5($tag);
229
    }
230
231
    /**
232
     * 序列化数据
233
     * @access protected
234
     * @param mixed $data 缓存数据
235 3
     * @return string
236
     */
237 3
    protected function serialize($data): string
238 3
    {
239
        if (is_numeric($data)) {
240
            return (string) $data;
241 3
        }
242
243 3
        $serialize = $this->options['serialize'][0] ?? "serialize";
244
245
        return $serialize($data);
246
    }
247
248
    /**
249
     * 反序列化数据
250
     * @access protected
251
     * @param string $data 缓存数据
252 3
     * @return mixed
253
     */
254 3
    protected function unserialize($data)
255 3
    {
256
        if (is_numeric($data)) {
257
            return $data;
258 3
        }
259
260 3
        $unserialize = $this->options['serialize'][1] ?? "unserialize";
261
262
        return $unserialize($data);
263
    }
264
265
    /**
266
     * 返回句柄对象,可执行其它高级方法
267
     *
268
     * @access public
269
     * @return object
270
     */
271
    public function handler()
272
    {
273
        return $this->handler;
274
    }
275
276
    /**
277
     * 返回缓存读取次数
278
     * @access public
279
     * @return int
280
     */
281
    public function getReadTimes(): int
282
    {
283
        return $this->readTimes;
284
    }
285
286
    /**
287
     * 返回缓存写入次数
288
     * @access public
289
     * @return int
290
     */
291
    public function getWriteTimes(): int
292
    {
293
        return $this->writeTimes;
294
    }
295
296
    /**
297
     * 读取缓存
298
     * @access public
299
     * @param iterable $keys    缓存变量名
300
     * @param mixed    $default 默认值
301
     * @return iterable
302 3
     * @throws InvalidArgumentException
303
     */
304 3
    public function getMultiple($keys, $default = null): iterable
305
    {
306 3
        $result = [];
307 3
308
        foreach ($keys as $key) {
309
            $result[$key] = $this->get($key, $default);
310 3
        }
311
312
        return $result;
313
    }
314
315
    /**
316
     * 写入缓存
317
     * @access public
318
     * @param iterable               $values 缓存数据
319
     * @param null|int|\DateInterval $ttl    有效时间 0为永久
320 3
     * @return bool
321
     */
322 3
    public function setMultiple($values, $ttl = null): bool
323 3
    {
324
        foreach ($values as $key => $val) {
325 3
            $result = $this->set($key, $val, $ttl);
326 1
327
            if (false === $result) {
328
                return false;
329
            }
330 3
        }
331
332
        return true;
333
    }
334
335
    /**
336
     * 删除缓存
337
     * @access public
338
     * @param iterable $keys 缓存变量名
339
     * @return bool
340 3
     * @throws InvalidArgumentException
341
     */
342 3
    public function deleteMultiple($keys): bool
343 3
    {
344
        foreach ($keys as $key) {
345 3
            $result = $this->delete($key);
346 1
347
            if (false === $result) {
348
                return false;
349
            }
350 3
        }
351
352
        return true;
353
    }
354
355
    public function __call($method, $args)
356
    {
357
        return call_user_func_array([$this->handler, $method], $args);
358
    }
359
}
360