api/shared/cache.php

77 lines
2.1 KiB
PHP
Raw Normal View History

2022-08-25 17:19:47 +02:00
<?php
/*
Copyright 2022 eraseyourknees
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
class UupDumpCache {
private $cacheFile;
2022-08-25 17:31:20 +02:00
private $newCacheVersion = 1;
2022-08-25 17:19:47 +02:00
2022-08-29 03:36:33 +02:00
public function __construct($resource, private $isCompressed = true) {
2022-08-25 17:31:20 +02:00
$res = $resource."+cache_v".$this->newCacheVersion;
$cacheHash = hash('sha256', strtolower($res));
2022-08-29 03:36:33 +02:00
$ext = $isCompressed ? '.json.gz' : '.json';
2022-08-25 17:19:47 +02:00
$this->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;
}
2022-08-25 18:12:01 +02:00
$cache = @file_get_contents($cacheFile);
if($this->isCompressed) $cache = @gzdecode($cache);
2022-08-25 17:19:47 +02:00
$cache = json_decode($cache, 1);
$expires = $cache['expires'];
$isExpired = ($expires !== false) && (time() > $expires);
2022-08-25 17:44:37 +02:00
if(empty($cache['content']) || $isExpired) {
$this->delete();
2022-08-25 17:19:47 +02:00
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');
2022-08-25 18:12:01 +02:00
$cacheContent = json_encode($cache)."\n";
2022-08-25 18:46:36 +02:00
if($this->isCompressed) $cacheContent = @gzencode($cacheContent);
2022-08-25 18:12:01 +02:00
@file_put_contents($cacheFile, $cacheContent);
2022-08-25 17:19:47 +02:00
}
}