|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Koded package. |
| 5 | + * |
| 6 | + * (c) Mihail Binev <mihail@kodeart.com> |
| 7 | + * |
| 8 | + * Please view the LICENSE distributed with this source code |
| 9 | + * for the full copyright and license information. |
| 10 | + * |
| 11 | + */ |
| 12 | + |
| 13 | +namespace Koded\Caching\Client; |
| 14 | + |
| 15 | +use Psr\SimpleCache\CacheInterface; |
| 16 | + |
| 17 | +final class MemoryClient implements CacheInterface |
| 18 | +{ |
| 19 | + |
| 20 | + use ClientTrait, MultiplesTrait; |
| 21 | + |
| 22 | + private $storage = []; |
| 23 | + private $expiration = []; |
| 24 | + |
| 25 | + public function get($key, $default = null) |
| 26 | + { |
| 27 | + if (isset($this->expiration[$key]) && $this->expiration[$key] < time()) { |
| 28 | + $this->delete($key); |
| 29 | + |
| 30 | + return $default; |
| 31 | + } |
| 32 | + |
| 33 | + return $this->storage[$key] ?? $default; |
| 34 | + } |
| 35 | + |
| 36 | + public function set($key, $value, $ttl = null) |
| 37 | + { |
| 38 | + if ($ttl < 0 || $ttl === 0) { |
| 39 | + return $this->delete($key); |
| 40 | + } |
| 41 | + |
| 42 | + if ($ttl > 0) { |
| 43 | + $this->expiration[$key] = time() + $ttl; |
| 44 | + } |
| 45 | + |
| 46 | + $this->storage[$key] = $value; |
| 47 | + |
| 48 | + return true; |
| 49 | + } |
| 50 | + |
| 51 | + public function delete($key) |
| 52 | + { |
| 53 | + unset($this->storage[$key], $this->expiration[$key]); |
| 54 | + |
| 55 | + return false === array_key_exists($key, $this->storage); |
| 56 | + } |
| 57 | + |
| 58 | + public function clear() |
| 59 | + { |
| 60 | + $this->storage = []; |
| 61 | + $this->expiration = []; |
| 62 | + |
| 63 | + return true; |
| 64 | + } |
| 65 | + |
| 66 | + public function deleteMultiple($keys) |
| 67 | + { |
| 68 | + $deleted = 0; |
| 69 | + foreach ($keys as $key) { |
| 70 | + $this->delete($key) && ++$deleted; |
| 71 | + } |
| 72 | + |
| 73 | + return count($keys) === $deleted; |
| 74 | + } |
| 75 | + |
| 76 | + public function has($key) |
| 77 | + { |
| 78 | + return array_key_exists($key, $this->storage); |
| 79 | + } |
| 80 | +} |
0 commit comments