Completed
Push — master ( 5d72aa...20e171 )
by Hu
04:49 queued 01:59
created

FileCache::getItem()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 6.8395

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 21
ccs 10
cts 14
cp 0.7143
rs 8.7624
cc 6
eloc 13
nc 5
nop 1
crap 6.8395
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 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
     * 根据key获取值,会判断是否过期
37
     * @param $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
        return $cache_data['data'];
47
    }
48
49
    /**
50
     * 添加或覆盖一个key
51
     * @param $key
52
     * @param $value
53
     * @param $expire
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
    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 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
            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
            $this->delete($key);
244
            return false;
245
        }
246 12
    }
247
248
    /**
249
     * 检查key是否过期
250
     * @param $cache_data
251
     * @return bool
252
     */
253 12
    protected function checkExpire($cache_data)
254
    {
255 12
        $time = time();
256 12
        $is_expire = intval($cache_data['expire']) !== 0 && (intval($cache_data['time']) + intval($cache_data['expire']) < $time);
257 12
        if ($is_expire) return false;
258
259 12
        return true;
260
    }
261
}