mirror of
https://github.com/DirectoryLister/DirectoryLister.git
synced 2025-08-18 11:51:40 +02:00
Added the PruneCacheMiddleware
This commit is contained in:
@@ -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
|
||||
|
48
app/src/Middlewares/PruneCacheMiddleware.php
Normal file
48
app/src/Middlewares/PruneCacheMiddleware.php
Normal 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');
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user