diff --git a/app/config/cache.php b/app/config/cache.php index 903eb3c..bcf70f9 100644 --- a/app/config/cache.php +++ b/app/config/cache.php @@ -21,6 +21,15 @@ return [ */ 'cache_lifetime' => DI\env('CACHE_LIFETIME', 0), + /** + * Some cache drivers require manually pruning the cache periodically to + * remove expired items. This is the percentage chance (out of 100) of a + * request "winning" the lottery causing the cache to be pruned. + * + * Default value: 2 + */ + 'cache_lottery' => DI\env('CACHE_LOTTERY', 2), + /** * Path to the view cache directory. Set to 'false' to disable * view caching entirely. The view cache is separate from the application diff --git a/app/src/Middlewares/PruneCacheMiddleware.php b/app/src/Middlewares/PruneCacheMiddleware.php new file mode 100644 index 0000000..5731a88 --- /dev/null +++ b/app/src/Middlewares/PruneCacheMiddleware.php @@ -0,0 +1,48 @@ +config = $config; + $this->cache = $cache; + } + + /** Invoke the CachePruneMiddleware class. */ + public function __invoke(Request $request, RequestHandler $handler): ResponseInterface + { + $response = $handler->handle($request); + + if (! $this->cache instanceof PruneableInterface) { + return $response; + } + + if ($this->winsLottery()) { + $this->cache->prune(); + } + + return $response; + } + + /** Determine if this request wins the lottery. */ + private function winsLottery(): bool + { + return random_int(1, 100) <= $this->config->get('cache_lottery'); + } +}