|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace IngeniozIT\Cache; |
| 6 | + |
| 7 | +use Psr\SimpleCache\CacheInterface; |
| 8 | +use Psr\Cache\CacheItemPoolInterface; |
| 9 | +use DateInterval; |
| 10 | + |
| 11 | +final readonly class SimpleCache implements CacheInterface |
| 12 | +{ |
| 13 | + public function __construct( |
| 14 | + private CacheItemPoolInterface $pool, |
| 15 | + ) { |
| 16 | + } |
| 17 | + |
| 18 | + public function get(string $key, mixed $default = null): mixed |
| 19 | + { |
| 20 | + $item = $this->pool->getItem($key); |
| 21 | + return $item->isHit() ? $item->get() : $default; |
| 22 | + } |
| 23 | + |
| 24 | + public function set(string $key, mixed $value, int|DateInterval|null $ttl = null): bool |
| 25 | + { |
| 26 | + $item = $this->pool->getItem($key); |
| 27 | + $item->set($value); |
| 28 | + $item->expiresAfter($ttl); |
| 29 | + return $this->pool->save($item); |
| 30 | + } |
| 31 | + |
| 32 | + public function delete(string $key): bool |
| 33 | + { |
| 34 | + return $this->pool->deleteItem($key); |
| 35 | + } |
| 36 | + |
| 37 | + public function clear(): bool |
| 38 | + { |
| 39 | + return $this->pool->clear(); |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * @param iterable<string> $keys |
| 44 | + * @return array<string, mixed> |
| 45 | + */ |
| 46 | + public function getMultiple(iterable $keys, mixed $default = null): iterable |
| 47 | + { |
| 48 | + $values = []; |
| 49 | + foreach ($keys as $key) { |
| 50 | + $item = $this->pool->getItem($key); |
| 51 | + $values[$key] = $item->isHit() ? $item->get() : $default; |
| 52 | + } |
| 53 | + return $values; |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * @param iterable<string, mixed> $values |
| 58 | + */ |
| 59 | + public function setMultiple(iterable $values, int|DateInterval|null $ttl = null): bool |
| 60 | + { |
| 61 | + foreach ($values as $key => $value) { |
| 62 | + $item = $this->pool->getItem($key); |
| 63 | + $item->set($value); |
| 64 | + $item->expiresAfter($ttl); |
| 65 | + $this->pool->saveDeferred($item); |
| 66 | + } |
| 67 | + return $this->pool->commit(); |
| 68 | + } |
| 69 | + |
| 70 | + public function deleteMultiple(iterable $keys): bool |
| 71 | + { |
| 72 | + $success = true; |
| 73 | + foreach ($keys as $key) { |
| 74 | + if (!$this->pool->deleteItem($key)) { |
| 75 | + $success = false; |
| 76 | + } |
| 77 | + } |
| 78 | + return $success; |
| 79 | + } |
| 80 | + |
| 81 | + public function has(string $key): bool |
| 82 | + { |
| 83 | + return $this->pool->hasItem($key); |
| 84 | + } |
| 85 | +} |
0 commit comments