Files::dec()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Cache\Files
5
 *
6
 * Core\Cache Files Driver.
7
 *
8
 * @package core
9
 * @author [email protected]
10
 * @copyright Caffeina srl - 2015 - http://caffeina.it
11
 */
12
13
namespace Cache;
14
15
class Files implements Adapter {
16
    protected $options;
17
18
    public static function valid(){
19
        return true;
20
    }
21
22
    public function __construct($options=[]){
23
        $this->options = (object) array_merge($options,[
24
            'cache_dir' => sys_get_temp_dir().'/core_file_cache',
25
        ]);
26
        $this->options->cache_dir = rtrim($this->options->cache_dir,'/');
27
        if(false===is_dir($this->options->cache_dir)) mkdir($this->options->cache_dir,0777,true);
28
        $this->options->cache_dir .= '/';
29
    }
30
31
    public function get($key){
32
        $cache_file_name = $this->options->cache_dir.$key.'.cache.php';
33
        if(is_file($cache_file_name) && $data = @unserialize(file_get_contents($cache_file_name))){
34
            if($data[0] && (time() > $data[0])) {
35
                unlink($cache_file_name);
36
                return null;
37
            }
38
            return $data[1];
39
        } else {
40
            return null;
41
        }
42
    }
43
44
    public function set($key,$value,$expire=0){
45
        $cache_file_name = $this->options->cache_dir.$key.'.cache.php';
46
        file_put_contents($cache_file_name,serialize([$expire?time()+$expire:0,$value]));
47
    }
48
49
    public function delete($key){
50
        $cache_file_name = $this->options->cache_dir.$key.'.cache.php';
51
      if(is_file($cache_file_name)) unlink($cache_file_name);
52
    }
53
54
    public function exists($key){
55
        $cache_file_name = $this->options->cache_dir.$key.'.cache.php';
56
        if(false === is_file($cache_file_name)) return false;
57
        $peek = file_get_contents($cache_file_name,false,null,-1,32);
58
        $expire = explode('{i:0;i:',$peek,2);
59
        $expire = explode(';',end($expire),2);
60
        $expire = current($expire);
61
        if($expire && $expire < time()){
62
            unlink($cache_file_name);
63
            return false;
64
        } else return true;
65
    }
66
67
    public function flush(){
68
        exec('rm -f ' . $this->options->cache_dir . '*.cache.php');
69
    }
70
71
    public function inc($key,$value=1){
72
        if(null === ($current = $this->get($key))) $current = $value; else $current += $value;
73
        $this->set($key,$current);
74
    }
75
76
    public function dec($key,$value=1){
77
        $this->inc($key,-abs($value));
78
    }
79
}
80