Psr7Middlewares\Middleware\Cache::__invoke PHP Method

__invoke() public method

Execute the middleware.
public __invoke ( Psr\Http\Message\RequestInterface $request, Psr\Http\Message\ResponseInterface $response, callable $next ) : Psr\Http\Message\ResponseInterface
$request Psr\Http\Message\RequestInterface
$response Psr\Http\Message\ResponseInterface
$next callable
return Psr\Http\Message\ResponseInterface
    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;
    }