|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Beste\Cache; |
| 4 | + |
| 5 | +use Psr\Cache\CacheItemInterface; |
| 6 | +use Psr\Cache\CacheItemPoolInterface; |
| 7 | +use Psr\Clock\ClockInterface; |
| 8 | + |
| 9 | +final class InMemoryCache implements CacheItemPoolInterface |
| 10 | +{ |
| 11 | + /** @var array<string, CacheItemInterface> */ |
| 12 | + private array $items; |
| 13 | + /** @var array<string, CacheItemInterface> */ |
| 14 | + private array $deferredItems; |
| 15 | + |
| 16 | + public function __construct(private readonly ClockInterface $clock) |
| 17 | + { |
| 18 | + $this->items = []; |
| 19 | + $this->deferredItems = []; |
| 20 | + } |
| 21 | + |
| 22 | + public function getItem(string $key): CacheItemInterface |
| 23 | + { |
| 24 | + $key = CacheKey::fromString($key); |
| 25 | + |
| 26 | + $item = $this->items[$key->toString()] ?? null; |
| 27 | + |
| 28 | + if ($item === null) { |
| 29 | + return new CacheItem($key, $this->clock); |
| 30 | + } |
| 31 | + |
| 32 | + return clone $item; |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * @return iterable<CacheItemInterface> |
| 37 | + */ |
| 38 | + public function getItems(array $keys = []): iterable |
| 39 | + { |
| 40 | + if ($keys === []) { |
| 41 | + return []; |
| 42 | + } |
| 43 | + |
| 44 | + $items = []; |
| 45 | + |
| 46 | + foreach ($keys as $key) { |
| 47 | + $items[$key] = $this->getItem($key); |
| 48 | + } |
| 49 | + |
| 50 | + return $items; |
| 51 | + } |
| 52 | + |
| 53 | + public function hasItem(string $key): bool |
| 54 | + { |
| 55 | + return $this->getItem($key)->isHit(); |
| 56 | + } |
| 57 | + |
| 58 | + public function clear(): bool |
| 59 | + { |
| 60 | + $this->items = []; |
| 61 | + $this->deferredItems = []; |
| 62 | + |
| 63 | + return true; |
| 64 | + } |
| 65 | + |
| 66 | + public function deleteItem(string $key): bool |
| 67 | + { |
| 68 | + $key = CacheKey::fromString($key); |
| 69 | + |
| 70 | + unset($this->items[$key->toString()]); |
| 71 | + |
| 72 | + return true; |
| 73 | + } |
| 74 | + |
| 75 | + public function deleteItems(array $keys): bool |
| 76 | + { |
| 77 | + foreach ($keys as $key) { |
| 78 | + $this->deleteItem($key); |
| 79 | + } |
| 80 | + |
| 81 | + return true; |
| 82 | + } |
| 83 | + |
| 84 | + public function save(CacheItemInterface $item): bool |
| 85 | + { |
| 86 | + $this->items[$item->getKey()] = $item; |
| 87 | + |
| 88 | + return true; |
| 89 | + } |
| 90 | + |
| 91 | + public function saveDeferred(CacheItemInterface $item): bool |
| 92 | + { |
| 93 | + $this->deferredItems[$item->getKey()] = $item; |
| 94 | + |
| 95 | + return true; |
| 96 | + } |
| 97 | + |
| 98 | + public function commit(): bool |
| 99 | + { |
| 100 | + foreach ($this->deferredItems as $item) { |
| 101 | + $this->save($item); |
| 102 | + } |
| 103 | + |
| 104 | + $this->deferredItems = []; |
| 105 | + |
| 106 | + return true; |
| 107 | + } |
| 108 | +} |
0 commit comments