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