MD_STD/src/MD_STD_CACHE.php

80 lines
2.2 KiB
PHP

<?PHP
/**
* Provides static functions for simple caching.
*
* @author Joshua Ramon Enslin <joshua@museum-digital.de>
*/
declare(strict_types = 1);
/**
* Provides caching functions.
*/
final class MD_STD_CACHE {
/**
* Shutdown function for caching contents of output buffer.
*
* @param Redis $redis Redis connection.
* @param string $redisKey Key to cache by in redis.
* @param integer $expiry Expiration time in seconds.
*
* @return void
*/
public static function shutdown_cache_through_redis(Redis $redis, string $redisKey, int $expiry = 3600):void {
$outputT = trim(MD_STD::minimizeHTMLString(MD_STD::ob_get_clean()));
echo $outputT;
$redis->set($redisKey, $outputT);
$redis->expire($redisKey, $expiry);
$redis->close();
}
/**
* Caches and serves a page through redis. Should be called at the start
* of the script generating a page.
*
* @param string $redisKey Key to cache by in redis.
* @param integer $expiry Expiration time in seconds.
* @param Redis $redis Redis connection.
*
* @return string
*/
public static function serve_page_through_redis_cache(Redis $redis, string $redisKey, int $expiry = 3600):string {
if (PHP_SAPI === 'cli') {
return '';
}
if ($redis->ping() !== false) {
ob_start();
if ($redisResult = $redis->get($redisKey)) {
if (strlen($redisResult) > 3 and strpos($redisResult, ' id="errorPage"') === false) {
$redis->close();
return $redisResult;
}
else {
register_shutdown_function(function(Redis $redis, string $redisKey, int $expiry) :void {
self::shutdown_cache_through_redis($redis, $redisKey, $expiry);
}, $redis, $redisKey, $expiry);
}
}
else {
register_shutdown_function(function(Redis $redis, string $redisKey, int $expiry) :void {
self::shutdown_cache_through_redis($redis, $redisKey, $expiry);
}, $redis, $redisKey, $expiry);
}
}
return '';
}
}