Completed
Push — 6.0 ( a4ef3c...64a49e )
by yun
04:55
created

Redis::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 11
ccs 5
cts 6
cp 0.8333
crap 2.0185
rs 10
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
12
namespace think\cache\driver;
13
14
use think\cache\Driver;
15
16
/**
17
 * Redis缓存驱动,适合单机部署、有前端代理实现高可用的场景,性能最好
18
 * 有需要在业务层实现读写分离、或者使用RedisCluster的需求,请使用Redisd驱动
19
 *
20
 * 要求安装phpredis扩展:https://github.com/nicolasff/phpredis
21
 * @author    尘缘 <[email protected]>
22
 */
23
class Redis extends Driver
24
{
25
    /** @var \Predis\Client|\Redis */
0 ignored issues
show
Bug introduced by
The type Predis\Client was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
26
    protected $handler;
27
28
    /**
29
     * 配置参数
30
     * @var array
31
     */
32
    protected $options = [
33
        'host'       => '127.0.0.1',
34
        'port'       => 6379,
35
        'password'   => '',
36
        'select'     => 0,
37
        'timeout'    => 0,
38
        'expire'     => 0,
39
        'persistent' => false,
40
        'prefix'     => '',
41
        'tag_prefix' => 'tag:',
42
        'serialize'  => [],
43
    ];
44
45
    /**
46
     * 架构函数
47
     * @access public
48
     * @param array $options 缓存参数
49
     */
50 1
    public function __construct(array $options = [])
51
    {
52 1
        if (!empty($options)) {
53 1
            $this->options = array_merge($this->options, $options);
54
        }
55
56 1
        if (extension_loaded('redis')) {
57 1
            $this->handler = new \Redis;
58
59 1
            if ($this->options['persistent']) {
60
                $this->handler->pconnect($this->options['host'], (int) $this->options['port'], $this->options['timeout'], 'persistent_id_' . $this->options['select']);
61
            } else {
62 1
                $this->handler->connect($this->options['host'], (int) $this->options['port'], $this->options['timeout']);
63
            }
64
65 1
            if ('' != $this->options['password']) {
66 1
                $this->handler->auth($this->options['password']);
67
            }
68
        } elseif (class_exists('\Predis\Client')) {
69
            $params = [];
70
            foreach ($this->options as $key => $val) {
71
                if (in_array($key, ['aggregate', 'cluster', 'connections', 'exceptions', 'prefix', 'profile', 'replication', 'parameters'])) {
72
                    $params[$key] = $val;
73
                    unset($this->options[$key]);
74
                }
75
            }
76
77
            if ('' == $this->options['password']) {
78
                unset($this->options['password']);
79
            }
80
81
            $this->handler = new \Predis\Client($this->options, $params);
82
83
            $this->options['prefix'] = '';
84
        } else {
85
            throw new \BadFunctionCallException('not support: redis');
86
        }
87
88 1
        if (0 != $this->options['select']) {
89
            $this->handler->select($this->options['select']);
90
        }
91 1
    }
92
93
    /**
94
     * 判断缓存
95
     * @access public
96
     * @param string $name 缓存变量名
97
     * @return bool
98
     */
99
    public function has($name): bool
100
    {
101
        return $this->handler->exists($this->getCacheKey($name));
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->handler->e...is->getCacheKey($name)) returns the type integer which is incompatible with the type-hinted return boolean.
Loading history...
102
    }
103
104
    /**
105
     * 读取缓存
106
     * @access public
107
     * @param string $name    缓存变量名
108
     * @param mixed  $default 默认值
109
     * @return mixed
110
     */
111 1
    public function get($name, $default = null)
112
    {
113 1
        $this->readTimes++;
114
115 1
        $value = $this->handler->get($this->getCacheKey($name));
116
117 1
        if (false === $value) {
118
            return $default;
119
        }
120
121 1
        return $this->unserialize($value);
122
    }
123
124
    /**
125
     * 写入缓存
126
     * @access public
127
     * @param string            $name   缓存变量名
128
     * @param mixed             $value  存储数据
129
     * @param integer|\DateTime $expire 有效时间(秒)
130
     * @return bool
131
     */
132 1
    public function set($name, $value, $expire = null): bool
133
    {
134 1
        $this->writeTimes++;
135
136 1
        if (is_null($expire)) {
137 1
            $expire = $this->options['expire'];
138
        }
139
140 1
        $key    = $this->getCacheKey($name);
141 1
        $expire = $this->getExpireTime($expire);
142 1
        $value  = $this->serialize($value);
143
144 1
        if ($expire) {
145
            $this->handler->setex($key, $expire, $value);
146
        } else {
147 1
            $this->handler->set($key, $value);
148
        }
149
150 1
        return true;
151
    }
152
153
    /**
154
     * 自增缓存(针对数值缓存)
155
     * @access public
156
     * @param string $name 缓存变量名
157
     * @param int    $step 步长
158
     * @return false|int
159
     */
160 1
    public function inc(string $name, int $step = 1)
161
    {
162 1
        $this->writeTimes++;
163
164 1
        $key = $this->getCacheKey($name);
165
166 1
        return $this->handler->incrby($key, $step);
167
    }
168
169
    /**
170
     * 自减缓存(针对数值缓存)
171
     * @access public
172
     * @param string $name 缓存变量名
173
     * @param int    $step 步长
174
     * @return false|int
175
     */
176 1
    public function dec(string $name, int $step = 1)
177
    {
178 1
        $this->writeTimes++;
179
180 1
        $key = $this->getCacheKey($name);
181
182 1
        return $this->handler->decrby($key, $step);
183
    }
184
185
    /**
186
     * 删除缓存
187
     * @access public
188
     * @param string $name 缓存变量名
189
     * @return bool
190
     */
191 1
    public function delete($name): bool
192
    {
193 1
        $this->writeTimes++;
194
195 1
        $result = $this->handler->del($this->getCacheKey($name));
196 1
        return $result > 0;
197
    }
198
199
    /**
200
     * 清除缓存
201
     * @access public
202
     * @return bool
203
     */
204 1
    public function clear(): bool
205
    {
206 1
        $this->writeTimes++;
207
208 1
        $this->handler->flushDB();
209 1
        return true;
210
    }
211
212
    /**
213
     * 删除缓存标签
214
     * @access public
215
     * @param array $keys 缓存标识列表
216
     * @return void
217
     */
218 1
    public function clearTag(array $keys): void
219
    {
220
        // 指定标签清除
221 1
        $this->handler->del($keys);
222 1
    }
223
224
    /**
225
     * 追加(数组)缓存数据
226
     * @access public
227
     * @param string $name  缓存标识
228
     * @param mixed  $value 数据
229
     * @return void
230
     */
231 1
    public function push(string $name, $value): void
232
    {
233 1
        $this->handler->sAdd($name, $value);
234 1
    }
235
236
    /**
237
     * 获取标签包含的缓存标识
238
     * @access public
239
     * @param string $tag 缓存标签
240
     * @return array
241
     */
242 1
    public function getTagItems(string $tag): array
243
    {
244 1
        return $this->handler->sMembers($tag);
245
    }
246
247
}
248