Memory::has()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace Sugarcrm\UpgradeSpec\Cache\Adapter;
4
5
use Psr\SimpleCache\CacheInterface;
6
use Sugarcrm\UpgradeSpec\Cache\Exception\InvalidArgumentException;
7
8
/**
9
 * PSR-16 compatible memory based cache adapter.
10
 */
11
class Memory implements CacheInterface
12
{
13
    use AdapterTrait;
14
15
    /**
16
     * @var array
17
     */
18
    private $cache = [];
19
20
    /**
21
     * Memory constructor.
22
     *
23
     * @param $data
24
     * @param $ttl
25
     */
26
    public function __construct($data = [], $ttl = 3600)
27
    {
28
        $this->validateIterableKey($data);
29
30
        foreach ($data as $key => $value) {
31
            $this->cache[$key] = [time() + $ttl, $value];
32
        }
33
34
        $this->ttl = $ttl;
35
    }
36
37
    /**
38
     * @param string $key
39
     * @param null   $default
40
     *
41
     * @return mixed
42
     */
43
    public function get($key, $default = null)
44
    {
45
        $this->validateKey($key);
46
47
        if (!isset($this->cache[$key])) {
48
            return $default;
49
        }
50
51
        list($expire, $value) = $this->cache[$key];
52
        if (!is_null($expire) && $expire < time()) {
53
            $this->delete($key);
54
55
            return $default;
56
        }
57
58
        return $value;
59
    }
60
61
    /**
62
     * @param string $key
63
     * @param mixed  $value
64
     * @param null   $ttl
65
     *
66
     * @return bool
67
     *
68
     * @throws InvalidArgumentException
69
     */
70
    public function set($key, $value, $ttl = null)
71
    {
72
        $this->validateKey($key);
73
74
        $this->cache[$key] = [$this->getExpire($ttl), $value];
75
76
        return true;
77
    }
78
79
    /**
80
     * @param string $key
81
     *
82
     * @return bool
83
     */
84
    public function delete($key)
85
    {
86
        $this->validateKey($key);
87
88
        if (!$this->has($key)) {
89
            return false;
90
        }
91
92
        unset($this->cache[$key]);
93
94
        return true;
95
    }
96
97
    /**
98
     * @return bool
99
     */
100
    public function clear()
101
    {
102
        $this->cache = [];
103
104
        return true;
105
    }
106
107
    /**
108
     * @param string $key
109
     *
110
     * @return bool
111
     */
112
    public function has($key)
113
    {
114
        $this->validateKey($key);
115
116
        return isset($this->cache[$key]);
117
    }
118
}
119