Completed
Push — master ( 09c5b8...727f68 )
by Dmitry
02:52 queued 15s
created

Cache::wrap()   B

Complexity

Conditions 8
Paths 7

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 8.0291

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 18
ccs 12
cts 13
cp 0.9231
rs 7.7777
cc 8
eloc 13
nc 7
nop 2
crap 8.0291
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
        $expire = null;
58 39
        if (is_array($result) && array_key_exists('expire', $result)) {
59
            $expire = $result['expire'];
60 39
        } elseif (is_object($result) && property_exists($result, 'expire')) {
61 1
            $expire = $result->expire;
62
        }
63 39
        if ($expire && $expire > Carbon::now()->getTimestamp()) {
64 1
            $this->set($hash, $result);
65
        }
66 39
        return $result;
67
    }
68
}
69