Completed
Push — master ( f95115...c1f013 )
by Hu
02:59
created

FileCache   B

Complexity

Total Complexity 44

Size/Duplication

Total Lines 249
Duplicated Lines 18.88 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 44
c 1
b 0
f 1
lcom 1
cbo 0
dl 47
loc 249
rs 8.3396

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 4 8 3
A get() 0 7 3
A set() 0 4 1
A setItem() 0 13 3
B createCacheFile() 4 15 5
A has() 0 7 2
B increment() 19 19 5
B decrement() 20 20 5
A delete() 0 10 3
A flush() 0 4 1
A delTree() 0 8 3
A path() 0 5 1
B getItem() 0 20 6
A checkExpire() 0 8 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like FileCache often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FileCache, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Jenner
5
 * Date: 2016/6/22
6
 * Time: 16:18
7
 */
8
9
namespace Jenner\SimpleFork\Cache;
10
11
12
class FileCache implements CacheInterface
13
{
14
15
    /**
16
     * 缓存目录
17
     * @var
18
     */
19
    private $cache_dir;
20
21
    /**
22
     * @param $cache_dir
23
     * @throws \Exception
24
     */
25
    public function __construct($cache_dir)
26
    {
27
        $this->cache_dir = $cache_dir;
28 View Code Duplication
        if (!is_dir($cache_dir)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
29
            $make_dir_result = mkdir($cache_dir, 0755, true);
30
            if ($make_dir_result === false) throw new \Exception('Cannot create the cache directory');
31
        }
32
    }
33
34
35
    /**
36
     * 根据key获取值,会判断是否过期
37
     * @param $key
38
     * @param string $default
39
     * @return mixed
40
     */
41
    public function get($key, $default = null)
42
    {
43
        $cache_data = $this->getItem($key);
44
        if ($cache_data === false || !is_array($cache_data)) return $default;
45
46
        return $cache_data['data'];
47
    }
48
49
    /**
50
     * 添加或覆盖一个key
51
     * @param $key
52
     * @param $value
53
     * @param $expire
54
     * @return mixed
55
     */
56
    public function set($key, $value, $expire = 0)
57
    {
58
        return $this->setItem($key, $value, time(), $expire);
59
    }
60
61
    /**
62
     * 设置包含元数据的信息
63
     * @param $key
64
     * @param $value
65
     * @param $time
66
     * @param $expire
67
     * @return bool
68
     */
69
    private function setItem($key, $value, $time, $expire)
70
    {
71
        $cache_file = $this->createCacheFile($key);
72
        if ($cache_file === false) return false;
73
74
        $cache_data = array('data' => $value, 'time' => $time, 'expire' => $expire);
75
        $cache_data = json_encode($cache_data);
76
77
        $put_result = file_put_contents($cache_file, $cache_data);
78
        if ($put_result === false) return false;
79
80
        return true;
81
    }
82
83
    /**
84
     * 创建缓存文件
85
     * @param $key
86
     * @return bool|string
87
     */
88
    private function createCacheFile($key)
89
    {
90
        $cache_file = $this->path($key);
91
        if (!file_exists($cache_file)) {
92
            $directory = dirname($cache_file);
93 View Code Duplication
            if (!is_dir($directory)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
94
                $make_dir_result = mkdir($directory, 0755, true);
95
                if ($make_dir_result === false) return false;
96
            }
97
            $create_result = touch($cache_file);
98
            if ($create_result === false) return false;
99
        }
100
101
        return $cache_file;
102
    }
103
104
    /**
105
     * 判断Key是否存在
106
     * @param $key
107
     * @return mixed
108
     */
109
    public function has($key)
110
    {
111
        $value = $this->get($key);
112
        if ($value === false) return false;
113
114
        return true;
115
    }
116
117
    /**
118
     * 加法递增
119
     * @param $key
120
     * @param int $value
121
     * @return mixed
122
     */
123 View Code Duplication
    public function increment($key, $value = 1)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
124
    {
125
        $item = $this->getItem($key);
126
        if ($item === false) {
127
            $set_result = $this->set($key, $value);
128
            if ($set_result === false) return false;
129
            return $value;
130
        }
131
132
        $check_expire = $this->checkExpire($item);
133
        if ($check_expire === false) return false;
134
135
        $item['data'] += $value;
136
137
        $result = $this->setItem($key, $item['data'], $item['time'], $item['expire']);
138
        if ($result === false) return false;
139
140
        return $item['data'];
141
    }
142
143
    /**
144
     * 减法递增
145
     * @param $key
146
     * @param int $value
147
     * @return mixed
148
     */
149 View Code Duplication
    public function decrement($key, $value = 1)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
150
    {
151
        $item = $this->getItem($key);
152
        if ($item === false) {
153
            $value = 0 - $value;
154
            $set_result = $this->set($key, $value);
155
            if ($set_result === false) return false;
156
            return $value;
157
        }
158
159
        $check_expire = $this->checkExpire($item);
160
        if ($check_expire === false) return false;
161
162
        $item['data'] -= $value;
163
164
        $result = $this->setItem($key, $item['data'], $item['time'], $item['expire']);
165
        if ($result === false) return false;
166
167
        return $item['data'];
168
    }
169
170
    /**
171
     * 删除一个key,同事会删除缓存文件
172
     * @param $key
173
     * @return mixed
174
     */
175
    public function delete($key)
176
    {
177
        $cache_file = $this->path($key);
178
        if (file_exists($cache_file)) {
179
            $unlink_result = unlink($cache_file);
180
            if ($unlink_result === false) return false;
181
        }
182
183
        return true;
184
    }
185
186
    /**
187
     * 清楚所有缓存
188
     * @return mixed
189
     */
190
    public function flush()
191
    {
192
        return $this->delTree($this->cache_dir);
193
    }
194
195
    /**
196
     * 递归删除目录
197
     * @param $dir
198
     * @return bool
199
     */
200
    function delTree($dir)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
201
    {
202
        $files = array_diff(scandir($dir), array('.', '..'));
203
        foreach ($files as $file) {
204
            (is_dir("$dir/$file")) ? $this->delTree("$dir/$file") : unlink("$dir/$file");
205
        }
206
        return rmdir($dir);
207
    }
208
209
    /**
210
     * 根据key获取缓存文件路径
211
     *
212
     * @param  string $key
213
     * @return string
214
     */
215
    protected function path($key)
216
    {
217
        $parts = array_slice(str_split($hash = md5($key), 2), 0, 2);
218
        return $this->cache_dir . '/' . implode('/', $parts) . '/' . $hash;
219
    }
220
221
    /**
222
     * 获取含有元数据的信息
223
     * @param $key
224
     * @return bool|mixed|string
225
     */
226
    protected function getItem($key)
227
    {
228
        $cache_file = $this->path($key);
229
        if (!file_exists($cache_file) || !is_readable($cache_file)) {
230
            return false;
231
        }
232
233
        $cache_data = file_get_contents($cache_file);
234
        if (empty($cache_data)) return false;
235
        $cache_data = json_decode($cache_data, true);
236
        if ($cache_data) {
237
            $check_expire = $this->checkExpire($cache_data);
238
            if ($check_expire === false) {
239
                $this->delete($key);
240
                return false;
241
            }
242
        }
243
244
        return $cache_data;
245
    }
246
247
    /**
248
     * 检查key是否过期
249
     * @param $cache_data
250
     * @return bool
251
     */
252
    protected function checkExpire($cache_data)
253
    {
254
        $time = time();
255
        $is_expire = intval($cache_data['expire']) !== 0 && (intval($cache_data['time']) + intval($cache_data['expire']) < $time);
256
        if ($is_expire) return false;
257
258
        return true;
259
    }
260
}