-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCacheItem.php
executable file
·116 lines (104 loc) · 2.55 KB
/
CacheItem.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<?php
namespace MaplePHP\Cache;
use MaplePHP\Cache\Interfaces\CacheItemInterface;
use DateTimeInterface;
use DateInterval;
use DateTime;
class CacheItem implements CacheItemInterface
{
private $key;
private $value;
private $isHit;
private $expiresAt;
/**
* Store checke item to this middle hand class object for Cache pool
* @param string $key
*/
public function __construct(string $key)
{
$this->key = $key;
$this->isHit = false;
}
/**
* Get cache item key
* @return string
*/
public function getKey(): string
{
return $this->key;
}
/**
* Get cache item
* @return mixed
*/
public function get(): mixed
{
return ($this->isHit()) ? $this->value : null;
}
/**
* Confirms if the cache item lookup resulted in a cache hit.
* @return bool
*/
public function isHit(): bool
{
return $this->isHit;
}
/**
* Set cache item
* @param mixed $value
*/
public function set(mixed $value): static
{
$this->value = $value;
$this->isHit = true;
return $this;
}
/**
* Set expiration date with DateTimeInterface
* @param DateTimeInterface $expiration
* @return static
*/
public function expiresAt(?DateTimeInterface $expiration): static
{
$this->expiresAt = $expiration;
return $this;
}
/**
* Set expiration date with Int or DateInterval
* @param DateInterval|int|null $expiration
* @return static
*/
public function expiresAfter(DateInterval|int|null $expiration): static
{
$this->expiresAt = $this->getTTL($expiration);
return $this;
}
/**
* Return expiration
* @return int
*/
public function getExpiration(): int
{
if ($this->expiresAt instanceof DateTimeInterface) {
return $this->expiresAt->getTimestamp();
} elseif (is_int($this->expiresAt)) {
return $this->expiresAt;
} else {
throw new \InvalidArgumentException('Invalid expiration provided');
}
}
/**
* Get TTL
* @param DateInterval|int|null $interval
* @return int
*/
protected function getTTL(DateInterval|int|null $interval): int
{
if ($interval instanceof DateInterval) {
$ttl = ($interval->s + ($interval->i * 60) + ($interval->h * 3600) + ($interval->days * 86400));
} else {
$ttl = (int)$interval;
}
return $ttl;
}
}