Completed
Push — master ( e32f5d...09c5b8 )
by Dmitry
02:45
created

Cache::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Basis;
4
5
use Basis\Converter;
6
use Carbon\Carbon;
7
8
class Cache
9
{
10
    private $converter;
11
12 39
    public function __construct(Converter $converter)
13
    {
14 39
        $this->converter = $converter;
15 39
        if (!is_dir('.cache')) {
16 4
            mkdir('.cache');
17
        }
18 39
    }
19
20
    private $cache = [];
21
22 39
    public function exists($key)
23
    {
24 39
        $filename = '.cache/'.$key;
25 39
        if (file_exists($filename)) {
26 1
            if (!array_key_exists($key, $this->cache)) {
27
                $this->cache[$key] = include $filename;
28
            }
29 1
            return $this->cache[$key]['expire'] > Carbon::now()->getTimestamp();
30
        }
31 39
    }
32
33 1
    public function get($key)
34
    {
35 1
        if ($this->exists($key)) {
36 1
            return $this->converter->toObject($this->cache[$key]);
37
        }
38
    }
39
40 1
    public function set($key, $value)
41
    {
42 1
        $filename = '.cache/'.$key;
43 1
        $data = $this->converter->toArray($value);
44 1
        $string = '<?php return '.var_export($data, true).';';
45
46 1
        file_put_contents($filename, $string);
47 1
        $this->cache[$key] = $data;
48 1
    }
49
50 39
    public function wrap($key, $callback)
51
    {
52 39
        $hash = md5(json_encode($key));
53 39
        if ($this->exists($hash)) {
54 1
            return $this->get($hash);
55
        }
56 39
        $result = call_user_func($callback);
57 39
        if (is_array($result) && array_key_exists('expire', $result) && $result['expire'] > Carbon::now()->getTimestamp()) {
58
            $this->set($hash, $result);
59
60 39
        } elseif (is_object($result) && property_exists($result, 'expire') && $result->expire > Carbon::now()->getTimestamp()) {
61 1
            $this->set($hash, $result);
62
        }
63 39
        return $result;
64
    }
65
}
66