diff options
Diffstat (limited to 'lib/classes/cache/MemoryCache.php')
| -rw-r--r-- | lib/classes/cache/MemoryCache.php | 98 |
1 files changed, 98 insertions, 0 deletions
diff --git a/lib/classes/cache/MemoryCache.php b/lib/classes/cache/MemoryCache.php new file mode 100644 index 0000000..7c00753 --- /dev/null +++ b/lib/classes/cache/MemoryCache.php @@ -0,0 +1,98 @@ +<?php + +namespace Studip\Cache; + +use DateTime; +use Psr\Cache\CacheItemInterface; + +/** + * The php memory implementation of the StudipCache interface. + * + * @author Jan-Hendrik Willms <tleilax+studip@gmail.com> + * @license GPL2 or any later version + * @since Stud.IP 5.0 + */ +class MemoryCache extends Cache +{ + protected array $memory_cache = []; + + /** + * Expires just a single key. + * + * @param string $arg the key + */ + public function expire($arg) + { + unset($this->memory_cache[$arg]); + } + + /** + * Expire all items from the cache. + */ + public function flush() + { + $this->memory_cache = []; + } + + public static function getDisplayName(): string + { + return 'Memory cache'; + } + + public function getStats(): array + { + return []; + } + + public static function getConfig(): array + { + return []; + } + + /** + * @inheritDoc + */ + public function getItem(string $key): CacheItemInterface + { + $item = new Item($key); + if (!isset($this->memory_cache[$key])) { + return $item; + } + if ($this->memory_cache[$key]['expires'] < time()) { + $this->expire($key); + return $item; + } + $item->setHit(); + $item->set($this->memory_cache[$key]['data']); + if (!empty($this->memory_cache[$key]['expires'])) { + $expiration = new DateTime(); + $expiration->setTimestamp($this->memory_cache[$key]['expires']); + $item->expiresAt($expiration); + } + return $item; + } + + /** + * @inheritDoc + */ + public function hasItem(string $key): bool + { + return isset($this->memory_cache[$key]) + && $this->memory_cache[$key]['expires'] < time(); + } + + /** + * @inheritDoc + */ + public function save(CacheItemInterface $item): bool + { + $expiration = $this->getExpiration($item); + + $this->memory_cache[$item->getKey()] = [ + 'expires' => $expiration + time(), + 'data' => $item->get(), + ]; + + return true; + } +} |
