-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMemoryClient.php
More file actions
84 lines (73 loc) · 2.12 KB
/
Copy pathMemoryClient.php
File metadata and controls
84 lines (73 loc) · 2.12 KB
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
<?php
/*
* This file is part of the Koded package.
*
* (c) Mihail Binev <mihail@kodeart.com>
*
* Please view the LICENSE distributed with this source code
* for the full copyright and license information.
*/
namespace Koded\Caching\Client;
use Koded\Caching\Cache;
use function array_key_exists;
use function Koded\Caching\verify_key;
use function Koded\Stdlib\now;
/**
* @property MemoryClient client
*/
final class MemoryClient implements Cache
{
use ClientTrait, MultiplesTrait;
private array $storage = [];
private array $expiration = [];
public function __construct(null|int $ttl = null)
{
$this->ttl = $ttl;
}
public function get(string $key, mixed $default = null): mixed
{
return $this->has($key) ? $this->storage[$key] : $default;
}
public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool
{
verify_key($key);
if (1 > $expiration = $this->timestampWithGlobalTtl($ttl, Cache::DATE_FAR_FAR_AWAY)) {
unset($this->storage[$key], $this->expiration[$key]);
} else {
// Loose the reference to the object
$this->storage[$key] = \is_object($value) ? clone $value : $value;
$this->expiration[$key] = $expiration;
}
return true;
}
public function delete(string $key): bool
{
if (false === $this->has($key)) {
return true;
}
unset($this->storage[$key], $this->expiration[$key]);
return true;
}
public function clear(): bool
{
$this->storage = [];
$this->expiration = [];
return true;
}
public function has(string $key): bool
{
verify_key($key);
if (false === array_key_exists($key, $this->expiration)) {
return false;
}
if ($this->expiration[$key] <= now()->getTimestamp()) {
unset($this->storage[$key], $this->expiration[$key]);
return false;
}
return true;
}
public function getExpirationFor(string $key): ?int
{
return $this->expiration[$key] ?? null;
}
}