MemoryCache::get()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 16
ccs 8
cts 8
cp 1
rs 9.4286
cc 3
eloc 8
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Phloppy\Cache;
4
5
class MemoryCache implements CacheInterface
6
{
7
8
    /**
9
     * @var array
10
     */
11
    protected $records = [];
12
13
14
    /**
15
     * Retrieve the nodes under the given key.
16
     *
17
     * @param string $key
18
     *
19
     * @return string[]
20
     */
21 4
    public function get($key)
22
    {
23 4
        if (!isset($this->records[$key])) {
24 1
            return null;
25
        }
26
27 4
        $record = $this->records[$key];
28
29 4
        if ($record['expire'] < time()) {
30 2
            unset($this->records[$key]);
31
32 2
            return null;
33
        }
34
35 4
        return $record['nodes'];
36
    }
37
38
39
    /**
40
     * Cache the given Nodes.
41
     *
42
     * @param string   $key
43
     * @param string[] $nodes
44
     * @param int      $ttl TTL in seconds.
45
     *
46
     * @return bool
47
     */
48 6
    public function set($key, array $nodes, $ttl)
49
    {
50 6
        $this->records[$key] = ['nodes' => $nodes, 'expire' => time() + $ttl];
51
52 6
        return true;
53
    }
54
55
56
    /**
57
     * Return seconds left until the key expires.
58
     *
59
     * @param string $key
60
     *
61
     * @return int The number of seconds the key is valid. 0 if expired or unknown.
62
     */
63 2
    public function expires($key)
64
    {
65 2
        if (!isset($this->records[$key])) {
66 1
            return 0;
67
        }
68
69 2
        return (int) max(0, $this->records[$key]['expire'] - time());
70
    }
71
}