mirror of
https://github.com/DirectoryLister/DirectoryLister.git
synced 2025-08-22 21:54:15 +02:00
Implemented custom CacheMiddleware
This commit is contained in:
@@ -96,4 +96,21 @@ return [
|
||||
$config->get('redis_port')
|
||||
);
|
||||
}),
|
||||
|
||||
/**
|
||||
* HTTP cache values for controlling browser page cache durations.
|
||||
*
|
||||
* Possible values: An array of content types mapped to their cache duration
|
||||
* in seconds
|
||||
*
|
||||
* Default value: [
|
||||
* 'application/json' => '300',
|
||||
* 'application/zip' => '300',
|
||||
* ]
|
||||
*/
|
||||
'http_cache' => [
|
||||
'application/json' => '300',
|
||||
'application/zip' => '300',
|
||||
],
|
||||
|
||||
];
|
||||
|
@@ -23,6 +23,7 @@ return [
|
||||
/** Array of application middlewares */
|
||||
'middlewares' => function (ContainerInterface $container): array {
|
||||
return [
|
||||
Middlewares\CacheMiddleware::class,
|
||||
Middlewares\ThemeMiddleware::class,
|
||||
Middlewares\WhoopsMiddleware::class,
|
||||
];
|
||||
|
34
app/src/Middlewares/CacheMiddleware.php
Normal file
34
app/src/Middlewares/CacheMiddleware.php
Normal file
@@ -0,0 +1,34 @@
|
||||
<?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;
|
||||
|
||||
class CacheMiddleware
|
||||
{
|
||||
/** @var Config The application configuration */
|
||||
protected $config;
|
||||
|
||||
/** Create a new CacheMiddleware. */
|
||||
public function __construct(Config $config)
|
||||
{
|
||||
$this->config = $config;
|
||||
}
|
||||
|
||||
/** Invoke the CacheMiddleware class. */
|
||||
public function __invoke(Request $request, RequestHandler $handler): ResponseInterface
|
||||
{
|
||||
$response = $handler->handle($request);
|
||||
|
||||
foreach ($this->config->get('http_cache') as $contentType => $age) {
|
||||
if (in_array($contentType, $response->getHeader('Content-Type'))) {
|
||||
return $response->withHeader('Cache-Control', sprintf('max-age=%d', $age));
|
||||
}
|
||||
}
|
||||
|
||||
return $response->withHeader('Cache-Control', 'max-age=0, must-revalidate');
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user