Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame^] | 1 | <?php |
| 2 | |
| 3 | namespace LdapRecord\Query; |
| 4 | |
| 5 | use Closure; |
| 6 | use DateInterval; |
| 7 | use DateTimeInterface; |
| 8 | use Psr\SimpleCache\CacheInterface; |
| 9 | |
| 10 | class Cache |
| 11 | { |
| 12 | use InteractsWithTime; |
| 13 | |
| 14 | /** |
| 15 | * The cache driver. |
| 16 | * |
| 17 | * @var CacheInterface |
| 18 | */ |
| 19 | protected $store; |
| 20 | |
| 21 | /** |
| 22 | * Constructor. |
| 23 | * |
| 24 | * @param CacheInterface $store |
| 25 | */ |
| 26 | public function __construct(CacheInterface $store) |
| 27 | { |
| 28 | $this->store = $store; |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * Get an item from the cache. |
| 33 | * |
| 34 | * @param string $key |
| 35 | * |
| 36 | * @return mixed |
| 37 | */ |
| 38 | public function get($key) |
| 39 | { |
| 40 | return $this->store->get($key); |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Store an item in the cache. |
| 45 | * |
| 46 | * @param string $key |
| 47 | * @param mixed $value |
| 48 | * @param DateTimeInterface|DateInterval|int|null $ttl |
| 49 | * |
| 50 | * @return bool |
| 51 | */ |
| 52 | public function put($key, $value, $ttl = null) |
| 53 | { |
| 54 | $seconds = $this->secondsUntil($ttl); |
| 55 | |
| 56 | if ($seconds <= 0) { |
| 57 | return $this->delete($key); |
| 58 | } |
| 59 | |
| 60 | return $this->store->set($key, $value, $seconds); |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Get an item from the cache, or execute the given Closure and store the result. |
| 65 | * |
| 66 | * @param string $key |
| 67 | * @param DateTimeInterface|DateInterval|int|null $ttl |
| 68 | * @param Closure $callback |
| 69 | * |
| 70 | * @return mixed |
| 71 | */ |
| 72 | public function remember($key, $ttl, Closure $callback) |
| 73 | { |
| 74 | $value = $this->get($key); |
| 75 | |
| 76 | if (! is_null($value)) { |
| 77 | return $value; |
| 78 | } |
| 79 | |
| 80 | $this->put($key, $value = $callback(), $ttl); |
| 81 | |
| 82 | return $value; |
| 83 | } |
| 84 | |
| 85 | /** |
| 86 | * Delete an item from the cache. |
| 87 | * |
| 88 | * @param string $key |
| 89 | * |
| 90 | * @return bool |
| 91 | */ |
| 92 | public function delete($key) |
| 93 | { |
| 94 | return $this->store->delete($key); |
| 95 | } |
| 96 | |
| 97 | /** |
| 98 | * Get the underlying cache store. |
| 99 | * |
| 100 | * @return CacheInterface |
| 101 | */ |
| 102 | public function store() |
| 103 | { |
| 104 | return $this->store; |
| 105 | } |
| 106 | } |