Cache::disableCache()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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