aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/cache/MemoryCache.php
diff options
context:
space:
mode:
authorPhilipp Schüttlöffel <schuettloeffel@zqs.uni-hannover.de>2024-09-24 10:53:31 +0200
committerPhilipp Schüttlöffel <schuettloeffel@zqs.uni-hannover.de>2024-09-24 10:53:31 +0200
commit4459dd7917f4d1c34f40bb68f0e991e9c3d53e4c (patch)
tree5c07151ae61276d334e88f6309c30d439a85c12e /lib/classes/cache/MemoryCache.php
parentda0022e5c1abbf9825ae76debaabdff7e8623bb4 (diff)
parent97a188592c679890a25c37ab78463add76a52ff7 (diff)
Merge branch 'main' into issue-3911issue-3911
Diffstat (limited to 'lib/classes/cache/MemoryCache.php')
-rw-r--r--lib/classes/cache/MemoryCache.php98
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;
+ }
+}