public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next)
{
$key = $this->getCacheKey($request);
$item = $this->cache->getItem($key);
//If it's cached
if ($item->isHit()) {
$headers = $item->get();
$cachedResponse = $response->withStatus(304);
foreach ($headers as $name => $header) {
$cachedResponse = $cachedResponse->withHeader($name, $header);
}
if ($this->cacheUtil->isNotModified($request, $cachedResponse)) {
return $cachedResponse;
}
$this->cache->deleteItem($key);
}
$response = $next($request, $response);
//Add cache-control header
if ($this->cacheControl && !$response->hasHeader('Cache-Control')) {
$response = $this->cacheUtil->withCacheControl($response, $this->cacheControl);
}
//Add Last-Modified header
if (!$response->hasHeader('Last-Modified')) {
$response = $this->cacheUtil->withLastModified($response, time());
}
//Save in the cache
if ($this->cacheUtil->isCacheable($response)) {
$item->set($response->getHeaders());
$item->expiresAfter($this->cacheUtil->getLifetime($response));
$this->cache->save($item);
}
return $response;
}