typecode
PHPCache Manager/CacheManager.php
1<?php
2
3declare(strict_types=1);
4
5readonly class CacheEntry
6{
7 public function __construct(
8 public mixed $value,
9 public int $expiresAt,
10 public int $hits = 0,
11 ) {}
12
13 public function isExpired(): bool
14 {
15 return time() > $this->expiresAt;
16 }
17}
18
19class CacheManager
20{
21 /** @var array<string, CacheEntry> */
22 private array $store = [];
23 private int $defaultTtl;
24
25 public function __construct(
26 private readonly int $maxSize = 1000,
27 int $ttl = 3600,
28 ) {
29 $this->defaultTtl = $ttl;
30 }
31
32 public function get(string $key, mixed $default = null): mixed
33 {
34 if (!isset($this->store[$key])) {
35 return $default;
36 }
37 $entry = $this->store[$key];
38 if ($entry->isExpired()) {
39 unset($this->store[$key]);
40 return $default;
41 }
42 $this->store[$key] = new CacheEntry(
43 value: $entry->value,
44 expiresAt: $entry->expiresAt,
45 hits: $entry->hits + 1,
46 );
47 return $entry->value;
48 }
49
50 public function set(string $key, mixed $value, ?int $ttl = null): void
51 {
52 if (count($this->store) >= $this->maxSize) {
53 $this->evictExpired();
54 }
55 $this->store[$key] = new CacheEntry(
56 value: $value,
57 expiresAt: time() + ($ttl ?? $this->defaultTtl),
58 );
59 }
60
61 private function evictExpired(): void
62 {
63 $this->store = array_filter(
64 $this->store,
65 fn(CacheEntry $e) => !$e->isExpired(),
66 );
67 }
68}
0WPM
100%Accuracy
00:00Time
0%
Progress