FileCache   B
last analyzed

Complexity

Total Complexity 44

Size/Duplication

Total Lines 252
Duplicated Lines 15.48 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 69.69%

Importance

Changes 0
Metric Value
wmc 44
lcom 1
cbo 0
dl 39
loc 252
ccs 69
cts 99
cp 0.6969
rs 8.3396
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 3
A get() 0 7 3
A set() 0 4 1
A setItem() 0 13 3
B createCacheFile() 0 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 23 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 string $cache_dir
23
     * @throws \Exception
24
     */
25 12
    public function __construct($cache_dir)
26
    {
27 12
        $this->cache_dir = $cache_dir;
28 12
        if (!is_dir($cache_dir)) {
29 12
            $make_dir_result = mkdir($cache_dir, 0755, true);
30 12
            if ($make_dir_result === false) throw new \Exception('Cannot create the cache directory');
31 12
        }
32 12
    }
33
34
35
    /**
36
     * get value by key, and check if it is expired
37
     * @param string $key
38
     * @param string $default
39
     * @return mixed
40
     */
41 12
    public function get($key, $default = null)
42
    {
43 12
        $cache_data = $this->getItem($key);
44 12
        if ($cache_data === false || !is_array($cache_data)) return $default;
45
46 12
        return $cache_data['data'];
47
    }
48
49
    /**
50
     * 添加或覆盖一个key
51
     * @param string $key
52
     * @param mixed $value
53
     * @param int $expire expire time in seconds
54
     * @return mixed
55
     */
56 12
    public function set($key, $value, $expire = 0)
57
    {
58 12
        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 12
    private function setItem($key, $value, $time, $expire)
70
    {
71 12
        $cache_file = $this->createCacheFile($key);
72 12
        if ($cache_file === false) return false;
73
74 12
        $cache_data = array('data' => $value, 'time' => $time, 'expire' => $expire);
75 12
        $cache_data = serialize($cache_data);
76
77 12
        $put_result = file_put_contents($cache_file, $cache_data);
78 12
        if ($put_result === false) return false;
79
80 12
        return true;
81
    }
82
83
    /**
84
     * 创建缓存文件
85
     * @param $key
86
     * @return bool|string
87
     */
88 12
    private function createCacheFile($key)
89
    {
90 12
        $cache_file = $this->path($key);
91 12
        if (!file_exists($cache_file)) {
92 12
            $directory = dirname($cache_file);
93 12
            if (!is_dir($directory)) {
94 12
                $make_dir_result = mkdir($directory, 0755, true);
95 12
                if ($make_dir_result === false) return false;
96 12
            }
97 12
            $create_result = touch($cache_file);
98 12
            if ($create_result === false) return false;
99 12
        }
100
101 12
        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 boolean
174
     */
175 12
    public function delete($key)
176
    {
177 12
        $cache_file = $this->path($key);
178 12
        if (file_exists($cache_file)) {
179 12
            $unlink_result = unlink($cache_file);
180 12
            if ($unlink_result === false) return false;
181 12
        }
182
183 12
        return true;
184
    }
185
186
    /**
187
     * 清楚所有缓存
188
     * @return mixed
189
     */
190 12
    public function flush()
191
    {
192 12
        return $this->delTree($this->cache_dir);
193
    }
194
195
    /**
196
     * 递归删除目录
197
     * @param $dir
198
     * @return bool
199
     */
200 12
    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 12
        $files = array_diff(scandir($dir), array('.', '..'));
203 12
        foreach ($files as $file) {
204 12
            (is_dir("$dir/$file")) ? $this->delTree("$dir/$file") : unlink("$dir/$file");
205 12
        }
206 12
        return rmdir($dir);
207
    }
208
209
    /**
210
     * 根据key获取缓存文件路径
211
     *
212
     * @param  string $key
213
     * @return string
214
     */
215 12
    protected function path($key)
216
    {
217 12
        $parts = array_slice(str_split($hash = md5($key), 2), 0, 2);
218 12
        return $this->cache_dir . '/' . implode('/', $parts) . '/' . $hash;
219
    }
220
221
    /**
222
     * 获取含有元数据的信息
223
     * @param $key
224
     * @return bool|mixed|string
225
     */
226 12
    protected function getItem($key)
227
    {
228 12
        $cache_file = $this->path($key);
229 12
        if (!file_exists($cache_file) || !is_readable($cache_file)) {
230 12
            return false;
231
        }
232
233 12
        $data = file_get_contents($cache_file);
234 12
        if (empty($data)) return false;
235 12
        $cache_data = unserialize($data);
236
237 12
        if ($cache_data === false) {
238
            return false;
239
        }
240
241 12
        $check_expire = $this->checkExpire($cache_data);
242 12
        if ($check_expire === false) {
243 12
            $this->delete($key);
244 12
            return false;
245
        }
246
247 12
        return $cache_data;
248
    }
249
250
    /**
251
     * 检查key是否过期
252
     * @param $cache_data
253
     * @return bool
254
     */
255 12
    protected function checkExpire($cache_data)
256
    {
257 12
        $time = time();
258 12
        $is_expire = intval($cache_data['expire']) !== 0 && (intval($cache_data['time']) + intval($cache_data['expire']) < $time);
259 12
        if ($is_expire) return false;
260
261 12
        return true;
262
    }
263
}