aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/cache/MemoryCache.class.php
diff options
context:
space:
mode:
authorMoritz Strohm <strohm@data-quest.de>2024-05-14 07:22:47 +0000
committerJan-Hendrik Willms <tleilax+studip@gmail.com>2024-05-14 07:22:47 +0000
commit40bdfaf4415ff9f46e63435fc5e61049649802f2 (patch)
treef3ae85d9edaef23db555a829571ff968c21f9af5 /lib/classes/cache/MemoryCache.class.php
parent636039e25ccc6c33ae758bdb3ddfca4f68327948 (diff)
made Stud.IP cache compatible with PSR-6, re #3701
Merge request studip/studip!2570
Diffstat (limited to 'lib/classes/cache/MemoryCache.class.php')
-rw-r--r--lib/classes/cache/MemoryCache.class.php98
1 files changed, 98 insertions, 0 deletions
diff --git a/lib/classes/cache/MemoryCache.class.php b/lib/classes/cache/MemoryCache.class.php
new file mode 100644
index 0000000..93f6bbd
--- /dev/null
+++ b/lib/classes/cache/MemoryCache.class.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 the key
+ */
+ public function expire($key)
+ {
+ unset($this->memory_cache[$key]);
+ }
+
+ /**
+ * 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($key)
+ {
+ $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($key)
+ {
+ return isset($this->memory_cache[$key])
+ && $this->memory_cache[$key]['expires'] < time();
+ }
+
+ /**
+ * @inheritDoc
+ */
+ public function save(CacheItemInterface $item)
+ {
+ $expiration = $this->getExpiration($item);
+
+ $this->memory_cache[$item->getKey()] = [
+ 'expires' => $expiration + time(),
+ 'data' => $item->get(),
+ ];
+
+ return true;
+ }
+}