JsonFileCacheProvider::get()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 1
dl 0
loc 11
ccs 9
cts 9
cp 1
crap 3
rs 10
c 0
b 0
f 0
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
}