Completed
Push — master ( c385cb...b0036f )
by Wei
04:12
created

JsonFileCacheProvider::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * User: derekzhangv
4
 * Time: 2018/5/29 16:41
5
 */
6
namespace zhangv\wechat\cache;
7
class JsonFileCacheProvider implements CacheProvider{
8
	private $cacheDir = null;
9
10
	public function __construct($cacheDir = null){
11
		if(!$cacheDir) $this->cacheDir = __DIR__;
12
		else $this->cacheDir = $cacheDir;
13
	}
14
15
	public function set($key,$jsonobj,$expireAt){
16
		$data = $jsonobj;
17
		$data->expires_at = $expireAt;
18
		$file = "{$this->cacheDir}/{$key}.json";
19
		$fp = fopen($file, "w");
20
		fwrite($fp, json_encode($data));
0 ignored issues
show
Bug introduced by
It seems like $fp can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

20
		fwrite(/** @scrutinizer ignore-type */ $fp, json_encode($data));
Loading history...
21
		if ($fp) fclose($fp);
0 ignored issues
show
introduced by
$fp is of type resource|false, thus it always evaluated to false.
Loading history...
22
	}
23
24
	public function get($key){
25
		$file = "{$this->cacheDir}/{$key}.json";
26
		$cache = null;
27
		if(file_exists($file)){
28
			$cache = json_decode(file_get_contents($file));
29
		}
30
		return $cache;
31
	}
32
33
	public function clear($key){
34
		$file = "{$this->cacheDir}/{$key}.json";
35
		if (file_exists($file)) {
36
			unlink($file);
37
		}
38
	}
39
}