Completed
Push — master ( 547bbe...6c1ef8 )
by Dmitry
03:22
created

Cache   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 42.5%

Importance

Changes 3
Bugs 2 Features 0
Metric Value
wmc 16
c 3
b 2
f 0
lcom 1
cbo 2
dl 0
loc 66
ccs 17
cts 40
cp 0.425
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A exists() 0 10 3
A get() 0 6 2
A set() 0 12 1
B wrap() 0 18 8
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 35
    public function __construct(Converter $converter)
13
    {
14 35
        $this->converter = $converter;
15 35
        if (!is_dir('.cache')) {
16
            mkdir('.cache');
17
            chown('.cache', 'www-data');
18
            chgrp('.cache', 'www-data');
19
        }
20 35
    }
21
22
    private $cache = [];
23
24 35
    public function exists($key)
25
    {
26 35
        $filename = '.cache/'.$key;
27 35
        if (file_exists($filename)) {
28
            if (!array_key_exists($key, $this->cache)) {
29
                $this->cache[$key] = include $filename;
30
            }
31
            return $this->cache[$key]['expire'] > Carbon::now()->getTimestamp();
32
        }
33 35
    }
34
35
    public function get($key)
36
    {
37
        if ($this->exists($key)) {
38
            return $this->converter->toObject($this->cache[$key]);
39
        }
40
    }
41
42
    public function set($key, $value)
43
    {
44
        $filename = '.cache/'.$key;
45
        $data = $this->converter->toArray($value);
46
        $string = '<?php return '.var_export($data, true).';';
47
48
        file_put_contents($filename, $string);
49
        chown($filename, 'www-data');
50
        chgrp($filename, 'www-data');
51
52
        $this->cache[$key] = $data;
53
    }
54
55 35
    public function wrap($key, $callback)
56
    {
57 35
        $hash = md5(json_encode($key));
58 35
        if ($this->exists($hash)) {
59
            return $this->get($hash);
60
        }
61 35
        $result = call_user_func($callback);
62 35
        $expire = null;
63 35
        if (is_array($result) && array_key_exists('expire', $result)) {
64
            $expire = $result['expire'];
65 35
        } elseif (is_object($result) && property_exists($result, 'expire')) {
66
            $expire = $result->expire;
67
        }
68 35
        if ($expire && $expire > Carbon::now()->getTimestamp()) {
69
            $this->set($hash, $result);
70
        }
71 35
        return $result;
72
    }
73
}
74