Added the PruneCacheMiddleware

This commit is contained in:
Chris Kankiewicz
2021-06-25 10:36:30 -07:00
parent 66eac6a485
commit e79c1b7546
2 changed files with 57 additions and 0 deletions

View File

@@ -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

View File

@@ -0,0 +1,48 @@
<?php
namespace App\Middlewares;
use App\Config;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Symfony\Component\Cache\PruneableInterface;
use Symfony\Contracts\Cache\CacheInterface;
class PruneCacheMiddleware
{
/** @var Config The application configuration */
protected $config;
/** @var CacheInterface The application cache */
protected $cache;
/** Create a new CachePruneMiddleware object. */
public function __construct(Config $config, CacheInterface $cache)
{
$this->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');
}
}