File: /var/www/vhosts/creativefellows.nl/firstbrick.creativefellows.nl/src/Middleware/CacheMiddleware.php
<?php
namespace App\Middleware;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Routing\RouteContext;
use App\Cache\CacheInterface;
/**
* CORS middleware.
*/
final class CacheMiddleware implements MiddlewareInterface
{
public function __construct(
ContainerInterface $container,
ResponseFactoryInterface $responseFactory,
CacheInterface $cache
){
$this->container = $container;
$this->responseFactory = $responseFactory;
$this->cacheInterface = $cache;
}
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
): ResponseInterface {
// get url path
$requestPath = $request->getUri()->getPath();
/*
* get cache file
*/
if($this->container->get('settings')['use_cache'] === true){
$cache = $this->cacheInterface->get($requestPath);
if ($cache)
{ // instanceof File
$response = $this->responseFactory->createResponse();
$response = $response->withStatus($cache->getStatus());
foreach ($cache->getHeaders() as $header => $value)
{
$response = $response->withHeader($header, $value);
}
$response->getBody()->write($cache->getContent());
return $response;
}
$response = $handler->handle($request);
$body = (string) $response->getBody();
//$changed = $body->write("Test");
$this->cacheInterface->add(
$requestPath,
$body
);
}
return $handler->handle($request);
}
}