Completed
Push — master ( 9d27fa...db7209 )
by Hannes
02:39
created

CacheItem::getTTL()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 6

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 8.8571
cc 6
eloc 8
nc 6
nop 0
crap 6
1
<?php
2
namespace Madewithlove\IlluminatePsrCacheBridge\Laravel;
3
4
use DateInterval;
5
use DateTime;
6
use DateTimeInterface;
7
use Psr\Cache\CacheItemInterface;
8
9
class CacheItem implements CacheItemInterface
10
{
11
    /**
12
     * @var string
13
     */
14
    private $key;
15
16
    /**
17
     * @var mixed|null
18
     */
19
    private $value;
20
21
    /**
22
     * @var bool
23
     */
24
    private $hit;
25
26
    /**
27
     * @var \DateTimeInterface|\DateInterval|int
28
     */
29
    private $expires;
30
31
    /**
32
     * @param string $key
33
     * @param mixed $value
34
     * @param bool $hit
35
     */
36 31
    public function __construct($key, $value = null, $hit = false)
37
    {
38 31
        $this->key = $key;
39 31
        $this->value = $value;
40 31
        $this->hit = boolval($hit);
41 31
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 19
    public function getKey()
47
    {
48 19
        return $this->key;
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54 21
    public function get()
55
    {
56 21
        return $this->value;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62 16
    public function isHit()
63
    {
64 16
        return $this->hit;
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70 9
    public function set($value)
71
    {
72 9
        $this->value = $value;
73
74 9
        return $this;
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80 5
    public function expiresAt($expiration)
81
    {
82 5
        $this->expires = $expiration;
83
84 5
        return $this;
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90 4
    public function expiresAfter($time)
91
    {
92 4
        $this->expires = $time;
93
94 4
        return $this;
95
    }
96
97
    /**
98
     * @return int|null
99
     *   The amount of minutes this item should stay alive. Or null when no expires is given.
100
     */
101 21
    public function getTTL()
102
    {
103 21
        if (is_int($this->expires)) {
104 3
            return floor($this->expires / 60.0);
105
        }
106
107 18
        if ($this->expires instanceof DateTimeInterface) {
108 3
            $diff = (new DateTime())->diff($this->expires);
109
110 3
            return boolval($diff->invert) ? 0 : $diff->i;
111
        }
112
113 15
        if ($this->expires instanceof DateInterval) {
114 3
            return boolval($this->expires->invert) ? 0 : $this->expires->i;
115
        }
116 12
    }
117
}
118