Completed
Push — 6.0 ( 28cc55...ecaa46 )
by liu
03:26
created

Redis::__construct()   B

Complexity

Conditions 11
Paths 42

Size

Total Lines 44
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 0
Metric Value
cc 11
eloc 26
nc 42
nop 1
dl 0
loc 44
ccs 0
cts 25
cp 0
crap 132
rs 7.3166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
// +----------------------------------------------------------------------
1 ignored issue
show
Coding Style introduced by
You must use "/**" style comments for a file comment
Loading history...
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
use think\contract\CacheHandlerInterface;
16
17
/**
18
 * Redis缓存驱动,适合单机部署、有前端代理实现高可用的场景,性能最好
19
 * 有需要在业务层实现读写分离、或者使用RedisCluster的需求,请使用Redisd驱动
20
 *
21
 * 要求安装phpredis扩展:https://github.com/nicolasff/phpredis
22
 * @author    尘缘 <[email protected]>
1 ignored issue
show
Coding Style introduced by
Tag value for @author tag indented incorrectly; expected 1 spaces but found 4
Loading history...
23
 */
4 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
24
class Redis extends Driver implements CacheHandlerInterface
25
{
26
    /**
27
     * 配置参数
28
     * @var array
29
     */
30
    protected $options = [
31
        'host'       => '127.0.0.1',
32
        'port'       => 6379,
33
        'password'   => '',
34
        'select'     => 0,
35
        'timeout'    => 0,
36
        'expire'     => 0,
37
        'persistent' => false,
38
        'prefix'     => '',
39
        'tag_prefix' => 'tag_',
40
        'serialize'  => [],
41
    ];
42
43
    /**
44
     * 架构函数
45
     * @access public
46
     * @param  array $options 缓存参数
47
     */
48
    public function __construct(array $options = [])
49
    {
50
        if (!empty($options)) {
51
            $this->options = array_merge($this->options, $options);
52
        }
53
54
        if (extension_loaded('redis')) {
55
            $this->handler = new \Redis;
56
57
            if ($this->options['persistent']) {
58
                $this->handler->pconnect($this->options['host'], (int) $this->options['port'], $this->options['timeout'], 'persistent_id_' . $this->options['select']);
59
            } else {
60
                $this->handler->connect($this->options['host'], (int) $this->options['port'], $this->options['timeout']);
61
            }
62
63
            if ('' != $this->options['password']) {
64
                $this->handler->auth($this->options['password']);
65
            }
66
67
            if (0 != $this->options['select']) {
68
                $this->handler->select($this->options['select']);
69
            }
70
        } elseif (class_exists('\Predis\Client')) {
71
            $params = [];
72
            foreach ($this->options as $key => $val) {
73
                if (in_array($key, ['aggregate', 'cluster', 'connections', 'exceptions', 'prefix', 'profile', 'replication', 'parameters'])) {
74
                    $params[$key] = $val;
75
                    unset($this->options[$key]);
76
                }
77
            }
78
79
            if ('' == $this->options['password']) {
80
                unset($this->options['password']);
81
            }
82
83
            $this->handler = new \Predis\Client($this->options, $params);
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...
84
85
            if (0 != $this->options['select']) {
86
                $this->handler->select($this->options['select']);
87
            }
88
89
            $this->options['prefix'] = '';
90
        } else {
91
            throw new \BadFunctionCallException('not support: redis');
92
        }
93
    }
94
95
    /**
96
     * 判断缓存
97
     * @access public
98
     * @param  string $name 缓存变量名
99
     * @return bool
100
     */
101
    public function has($name): bool
102
    {
103
        return $this->handler->exists($this->getCacheKey($name));
104
    }
105
106
    /**
107
     * 读取缓存
108
     * @access public
109
     * @param  string $name 缓存变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
110
     * @param  mixed  $default 默认值
111
     * @return mixed
112
     */
113
    public function get($name, $default = false)
114
    {
115
        $this->readTimes++;
116
117
        $value = $this->handler->get($this->getCacheKey($name));
118
119
        if (is_null($value) || false === $value) {
120
            return $default;
121
        }
122
123
        return $this->unserialize($value);
124
    }
125
126
    /**
127
     * 写入缓存
128
     * @access public
129
     * @param  string            $name 缓存变量名
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
130
     * @param  mixed             $value  存储数据
131
     * @param  integer|\DateTime $expire  有效时间(秒)
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
132
     * @return bool
133
     */
134
    public function set($name, $value, $expire = null): bool
135
    {
136
        $this->writeTimes++;
137
138
        if (is_null($expire)) {
139
            $expire = $this->options['expire'];
140
        }
141
142
        if (!empty($this->tag) && !$this->has($name)) {
143
            $first = true;
144
        }
145
146
        $key    = $this->getCacheKey($name);
147
        $expire = $this->getExpireTime($expire);
148
149
        $value = $this->serialize($value);
150
151
        if ($expire) {
152
            $this->handler->setex($key, $expire, $value);
153
        } else {
154
            $this->handler->set($key, $value);
155
        }
156
157
        isset($first) && $this->setTagItem($key);
0 ignored issues
show
Bug introduced by
The method setTagItem() does not exist on think\cache\driver\Redis. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

157
        isset($first) && $this->/** @scrutinizer ignore-call */ setTagItem($key);
Loading history...
158
159
        return true;
160
    }
161
162
    /**
163
     * 自增缓存(针对数值缓存)
164
     * @access public
165
     * @param  string $name 缓存变量名
166
     * @param  int    $step 步长
167
     * @return false|int
168
     */
169
    public function inc(string $name, int $step = 1)
170
    {
171
        $this->writeTimes++;
172
173
        $key = $this->getCacheKey($name);
174
175
        return $this->handler->incrby($key, $step);
176
    }
177
178
    /**
179
     * 自减缓存(针对数值缓存)
180
     * @access public
181
     * @param  string $name 缓存变量名
182
     * @param  int    $step 步长
183
     * @return false|int
184
     */
185
    public function dec(string $name, int $step = 1)
186
    {
187
        $this->writeTimes++;
188
189
        $key = $this->getCacheKey($name);
190
191
        return $this->handler->decrby($key, $step);
192
    }
193
194
    /**
195
     * 删除缓存
196
     * @access public
197
     * @param  string $name 缓存变量名
198
     * @return bool
199
     */
200
    public function delete($name): bool
201
    {
202
        $this->writeTimes++;
203
204
        $this->handler->del($this->getCacheKey($name));
205
        return true;
206
    }
207
208
    /**
209
     * 清除缓存
210
     * @access public
211
     * @return bool
212
     */
213
    public function clear(): bool
214
    {
215
        $this->writeTimes++;
216
217
        $this->handler->flushDB();
218
        return true;
219
    }
220
221
    /**
222
     * 删除缓存标签
223
     * @access public
224
     * @param  array  $keys 缓存标识列表
225
     * @return void
226
     */
227
    public function clearTag(array $keys): void
228
    {
229
        // 指定标签清除
230
        $this->handler->del($keys);
231
    }
232
233
    /**
234
     * 追加(数组)缓存数据
235
     * @access public
236
     * @param  string $name 缓存标识
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
237
     * @param  mixed  $value 数据
238
     * @return void
239
     */
240
    public function push(string $name, $value): void
241
    {
242
        $this->handler->sAdd($name, $value);
243
    }
244
245
    /**
246
     * 获取标签包含的缓存标识
247
     * @access public
248
     * @param  string $tag 缓存标签
249
     * @return array
250
     */
251
    public function getTagItems(string $tag): array
252
    {
253
        return $this->handler->sMembers($tag);
254
    }
255
256
}
257