| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace AcyMailing\Libraries\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 |
final class SimpleStringCache |
| 24 |
{ |
| 25 |
/** |
| 26 |
* @var array<non-empty-string, string> |
| 27 |
*/ |
| 28 |
private $values = []; |
| 29 |
|
| 30 |
/** |
| 31 |
* Checks whether there is an entry stored for the given key. |
| 32 |
* |
| 33 |
* @param non-empty-string $key |
| 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 non-empty-string $key |
| 49 |
* |
| 50 |
* @throws \BadMethodCallException |
| 51 |
*/ |
| 52 |
public function get(string $key): string |
| 53 |
{ |
| 54 |
if (!$this->has($key)) { |
| 55 |
throw new \BadMethodCallException('You can only call `get` with a key for an existing value.', 1625996246); |
| 56 |
} |
| 57 |
|
| 58 |
return $this->values[$key]; |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Sets or overwrites an entry. |
| 63 |
* |
| 64 |
* @param non-empty-string $key |
| 65 |
* |
| 66 |
* @throws \InvalidArgumentException |
| 67 |
*/ |
| 68 |
public function set(string $key, string $value): void |
| 69 |
{ |
| 70 |
$this->assertNotEmptyKey($key); |
| 71 |
|
| 72 |
$this->values[$key] = $value; |
| 73 |
} |
| 74 |
|
| 75 |
/** |
| 76 |
* @throws \InvalidArgumentException |
| 77 |
*/ |
| 78 |
private function assertNotEmptyKey(string $key): void |
| 79 |
{ |
| 80 |
if ($key === '') { |
| 81 |
throw new \InvalidArgumentException('Please provide a non-empty key.', 1625995840); |
| 82 |
} |
| 83 |
} |
| 84 |
} |
| 85 |
|