From 6e4e53ade83a2dd8e37b1ea12d9c3a12170ba343 Mon Sep 17 00:00:00 2001 From: "eraseyourknees@gmail.com" <112027564+eraseyourknees@users.noreply.github.com> Date: Thu, 25 Aug 2022 17:19:47 +0200 Subject: [PATCH] Implement central caching class --- shared/cache.php | 68 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 shared/cache.php diff --git a/shared/cache.php b/shared/cache.php new file mode 100644 index 0000000..d626a42 --- /dev/null +++ b/shared/cache.php @@ -0,0 +1,68 @@ +cacheFile = 'cache/'.$cacheHash.$ext; + } + + public function getFileName() { + return $this->cacheFile; + } + + public function delete() { + @unlink($this->cacheFile); + } + + public function get() { + $cacheFile = $this->cacheFile; + + if(!file_exists($cacheFile)) { + return false; + } + + $cache = @gzdecode(@file_get_contents($cacheFile)); + $cache = json_decode($cache, 1); + + $expires = $cache['expires']; + $isExpired = ($expires !== false) && (time() > $expires); + + if(empty($cache['content']) && $isExpired) { + $this->deleteCache(); + return false; + } + + return $cache['content']; + } + + public function put($content, $validity) { + $cacheFile = $this->cacheFile; + $expires = $validity ? time() + $validity : false; + + $cache = array( + 'expires' => $expires, + 'content' => $content, + ); + + if(!file_exists('cache')) mkdir('cache'); + @file_put_contents($cacheFile, gzencode(json_encode($cache)."\n")); + } +}