MemoryCacheItem   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 93.1%

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 1
dl 0
loc 73
ccs 27
cts 29
cp 0.931
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A set() 0 6 1
A isHit() 0 4 1
A getKey() 0 4 1
A get() 0 7 2
A expiresAfter() 0 8 2
A expiresAt() 0 9 2
A getExpirationDate() 0 4 1
A getDriver() 0 4 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