MD_STD/src/MD_STD_CACHE.php

103 lines
2.6 KiB
PHP
Raw Normal View History

2020-11-30 19:08:20 +01:00
<?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 {
/** @var string */
public static string $redis_host = '127.0.0.1';
2020-11-30 19:19:44 +01:00
/** @var integer */
2020-11-30 19:08:20 +01:00
public static int $redis_port = 6379;
/**
* Opens a connection to redis.
*
* @return Redis
*/
public static function open_redis_default():Redis {
$redis = new Redis();
$redis->connect(self::$redis_host, self::$redis_port, 1, null, 0, 0, ['auth' => [MD_CONF::$redis_pw]]);
return $redis;
}
/**
* Shutdown function for caching contents of output buffer.
*
* @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(string $redisKey, int $expiry = 3600):void {
$outputT = trim(MD_STD::minimizeHTMLString(MD_STD::ob_get_clean()));
echo $outputT;
$redis = self::open_redis_default();
$redis->set($redisKey, $outputT);
$redis->expire($redisKey, $expiry);
$redis->close();
}
2020-11-30 19:08:20 +01:00
/**
* 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.
*
* @return string
2020-11-30 19:08:20 +01:00
*/
public static function serve_page_through_redis_cache(string $redisKey, int $expiry = 3600):string {
2020-11-30 19:08:20 +01:00
2021-02-06 20:08:37 +01:00
if (PHP_SAPI === 'cli') {
return '';
}
$redis = self::open_redis_default();
2020-11-30 19:08:20 +01:00
if ($redis->ping() !== false) {
ob_start();
2021-12-24 02:01:40 +01:00
if ($redisResult = $redis->get($redisKey)) {
if (strlen($redisResult) > 3 and strpos($redisResult, ' id="errorPage"') === false) {
$redis->close();
return $redisResult;
}
else {
register_shutdown_function(function(string $redisKey, int $expiry = 3600) :void {
self::shutdown_cache_through_redis($redisKey, $expiry);
}, $redisKey);
}
2020-11-30 19:08:20 +01:00
}
else {
register_shutdown_function(function(string $redisKey, int $expiry = 3600) :void {
self::shutdown_cache_through_redis($redisKey, $expiry);
2020-11-30 19:08:20 +01:00
}, $redisKey);
}
}
$redis->close();
return '';
2020-11-30 19:08:20 +01:00
}
}