-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInMemoryStorage.php
More file actions
63 lines (51 loc) · 1.53 KB
/
Copy pathInMemoryStorage.php
File metadata and controls
63 lines (51 loc) · 1.53 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
<?php
declare(strict_types=1);
namespace Snicco\Component\SignedUrl\Storage;
use Snicco\Component\SignedUrl\Exception\BadIdentifier;
use Snicco\Component\SignedUrl\SignedUrl;
use Snicco\Component\TestableClock\Clock;
use Snicco\Component\TestableClock\SystemClock;
final class InMemoryStorage implements SignedUrlStorage
{
/**
* @var array<string,array{expires_at: int, usages_left: int}>
*/
private array $links = [];
private Clock $clock;
public function __construct(?Clock $clock = null)
{
$this->clock = $clock ?? SystemClock::fromUTC();
}
public function gc(): void
{
foreach ($this->links as $key => $link) {
if ($link['expires_at'] < $this->clock->currentTimestamp()) {
unset($this->links[$key]);
}
}
}
public function store(SignedUrl $signed_url): void
{
$this->links[$signed_url->identifier()] = [
'expires_at' => $signed_url->expiresAt(),
'usages_left' => $signed_url->maxUsage(),
];
}
public function consume(string $identifier): void
{
if (! isset($this->links[$identifier])) {
throw BadIdentifier::for($identifier);
}
$prev = $this->links[$identifier]['usages_left'];
$new = $prev - 1;
if ($new < 1) {
unset($this->links[$identifier]);
} else {
$this->links[$identifier]['usages_left'] = $new;
}
}
public function all(): array
{
return $this->links;
}
}