JsonFileCacheProvider   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 35
ccs 25
cts 25
cp 1
rs 10
c 0
b 0
f 0
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 11 3
A clear() 0 4 2
A __construct() 0 3 2
A set() 0 7 2
1
<?php
2
/**
3
 * JsonFileCacheProvider
4
 *
5
 * @license MIT
6
 * @author zhangv
7
 */
8
namespace zhangv\wechat\pay\cache;
9
class JsonFileCacheProvider implements CacheProvider{
10
	private $cacheDir = null;
11
12 57
	public function __construct($cacheDir = null){
13 57
		if(!$cacheDir) $this->cacheDir = __DIR__;
14 3
		else $this->cacheDir = $cacheDir;
15 57
	}
16
17 4
	public function set($key,$jsonobj,$expireAt = null){
18 4
		$data = $jsonobj;
19 4
		$data->expires_at = $expireAt;
20 4
		$file = "{$this->cacheDir}/{$key}.json";
21 4
		if($fp = @fopen($file, "w")){
22 4
			fwrite($fp, json_encode($data));
23 4
			fclose($fp);
24
		}
25 4
	}
26
27 4
	public function get($key){
28 4
		$file = "{$this->cacheDir}/{$key}.json";
29 4
		$cache = null;
30 4
		if(file_exists($file)){
31 4
			$cache = json_decode(file_get_contents($file));
32 4
			if($cache->expires_at < time()){
33 1
				$cache = null;
34 1
				$this->clear($key);
35
			}
36
		}
37 4
		return $cache;
38
	}
39
40 4
	public function clear($key){
41 4
		$file = "{$this->cacheDir}/{$key}.json";
42 4
		if (file_exists($file)) {
43 4
			unlink($file);
44
		}
45
	}
46
}