SimpleStringCache.php
77 lines
| 1 | <?php |
| 2 | |
| 3 | declare (strict_types=1); |
| 4 | namespace ProfilePressVendor\Pelago\Emogrifier\Caching; |
| 5 | |
| 6 | /** |
| 7 | * This cache caches string values with string keys. It is not PSR-6-compliant. |
| 8 | * |
| 9 | * Usage: |
| 10 | * |
| 11 | * ```php |
| 12 | * $cache = new SimpleStringCache(); |
| 13 | * $cache->set($key, $value); |
| 14 | * … |
| 15 | * if ($cache->has($key) { |
| 16 | * $cachedValue = $cache->get($value); |
| 17 | * } |
| 18 | * ``` |
| 19 | * |
| 20 | * @internal |
| 21 | */ |
| 22 | final class SimpleStringCache |
| 23 | { |
| 24 | /** |
| 25 | * @var array<non-empty-string, string> |
| 26 | */ |
| 27 | private $values = []; |
| 28 | /** |
| 29 | * Checks whether there is an entry stored for the given key. |
| 30 | * |
| 31 | * @param non-empty-string $key |
| 32 | * |
| 33 | * @throws \InvalidArgumentException |
| 34 | */ |
| 35 | public function has(string $key): bool |
| 36 | { |
| 37 | $this->assertNotEmptyKey($key); |
| 38 | return isset($this->values[$key]); |
| 39 | } |
| 40 | /** |
| 41 | * Returns the entry stored for the given key, and throws an exception if the value does not exist |
| 42 | * (which helps keep the return type simple). |
| 43 | * |
| 44 | * @param non-empty-string $key |
| 45 | * |
| 46 | * @throws \BadMethodCallException |
| 47 | */ |
| 48 | public function get(string $key): string |
| 49 | { |
| 50 | if (!$this->has($key)) { |
| 51 | throw new \BadMethodCallException('You can only call `get` with a key for an existing value.', 1625996246); |
| 52 | } |
| 53 | return $this->values[$key]; |
| 54 | } |
| 55 | /** |
| 56 | * Sets or overwrites an entry. |
| 57 | * |
| 58 | * @param non-empty-string $key |
| 59 | * |
| 60 | * @throws \InvalidArgumentException |
| 61 | */ |
| 62 | public function set(string $key, string $value): void |
| 63 | { |
| 64 | $this->assertNotEmptyKey($key); |
| 65 | $this->values[$key] = $value; |
| 66 | } |
| 67 | /** |
| 68 | * @throws \InvalidArgumentException |
| 69 | */ |
| 70 | private function assertNotEmptyKey(string $key): void |
| 71 | { |
| 72 | if ($key === '') { |
| 73 | throw new \InvalidArgumentException('Please provide a non-empty key.', 1625995840); |
| 74 | } |
| 75 | } |
| 76 | } |
| 77 |