Cache   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 0
dl 0
loc 56
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setCache() 0 10 4
A getCache() 0 3 1
A hasCache() 0 3 1
A getCacheItem() 0 7 2
A setCacheItem() 0 11 3
A disableCache() 0 3 1
1
<?php
2
3
namespace Ez\DbLinker;
4
5
use Exception;
6
use stdClass;
7
use Cache\Adapter\Apcu\ApcuCachePool;
8
9
class Cache
10
{
11
    private $cache;
12
    private $defaultCache = "Cache\Adapter\Apcu\ApcuCachePool";
13
14
    public function __construct($cache = null)
15
    {
16
        $this->setCache($cache);
17
    }
18
19
    // null = set to default cache (Apcu)
20
    // false = disable cache
21
    // \Psr\Cache\CacheItemPoolInterface class
22
    private function setCache($cache = null) {
23
        if ($cache !== false && $cache === null) {
24
            $cache = new $this->defaultCache();
25
        }
26
27
        if ($cache) {
28
            assert($cache instanceof \Psr\Cache\CacheItemPoolInterface);
29
        }
30
        $this->cache = $cache;
31
    }
32
33
    public function getCache() {
34
        return $this->cache;
35
    }
36
37
    public function hasCache() {
38
        return (bool)$this->cache;
39
    }
40
41
    public function getCacheItem($key) {
42
        if ($this->hasCache()) {
43
            $cacheItem = $this->getCache()->getItem($key);
44
            return $cacheItem->get();
45
        }
46
        return null;
47
    }
48
49
    public function setCacheItem($key, $data, $ttl = 0) {
50
        if ($this->hasCache()) {
51
            $cacheItem = $this->getCache()->getItem($key);
52
            $cacheItem->set($data);
53
            if ($ttl > 0) {
54
                $cacheItem->expiresAt(time()+$ttl);
55
            }
56
            return $this->getCache()->save($cacheItem);
57
        }
58
        return null;
59
    }
60
61
    public function disableCache() {
62
        $this->setCache(false);
63
    }
64
}
65