MemoryCacheItem::isHit()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace PhpAbac\Cache\Item;
4
5
use Psr\Cache\CacheItemInterface;
6
7
use PhpAbac\Cache\Exception\ExpiredCacheException;
8
9
class MemoryCacheItem implements CacheItemInterface
10
{
11
    /** @var string **/
12
    protected $key;
13
    /** @var mixed **/
14
    protected $value;
15
    /** @var int **/
16
    protected $defaultLifetime = 3600;
17
    /** @var \DateTime **/
18
    protected $expiresAt;
19
    /** @var string **/
20
    protected $driver = 'memory';
21
22 20
    public function __construct(string $key, int $ttl = null)
23
    {
24 20
        $this->key = $key;
25 20
        $this->expiresAfter($ttl);
26 20
    }
27
28 8
    public function set($value): MemoryCacheItem
29
    {
30 8
        $this->value = $value;
31
32 8
        return $this;
33
    }
34
35 11
    public function isHit(): bool
36
    {
37 11
        return $this->expiresAt >= new \DateTime();
38
    }
39
40 14
    public function getKey(): string
41
    {
42 14
        return $this->key;
43
    }
44
45 9
    public function get()
46
    {
47 9
        if (!$this->isHit()) {
48
            throw new ExpiredCacheException('Cache item is expired');
49
        }
50 9
        return $this->value;
51
    }
52
53 20
    public function expiresAfter($time): MemoryCacheItem
54
    {
55 20
        $lifetime = ($time !== null) ? $time : $this->defaultLifetime;
56
57 20
        $this->expiresAt = (new \DateTime())->setTimestamp(time() + $lifetime);
58
59 20
        return $this;
60
    }
61
62 2
    public function expiresAt($expiration): MemoryCacheItem
63
    {
64 2
        $this->expiresAt =
65 2
            ($expiration === null)
66
            ? (new \DateTime())->setTimestamp(time() + $this->defaultLifetime)
67 2
            : $expiration
68
        ;
69 2
        return $this;
70
    }
71
72 2
    public function getExpirationDate(): \DateTime
73
    {
74 2
        return $this->expiresAt;
75
    }
76
77 2
    public function getDriver(): string
78
    {
79 2
        return $this->driver;
80
    }
81
}
82