public function cache(RequestInterface $request, Response $response) { $currentTime = time(); $ttl = $request->getParams()->get('cache.override_ttl') ?: $response->getMaxAge() ?: $this->defaultTtl; if ($cacheControl = $response->getHeader('Cache-Control')) { $stale = $cacheControl->getDirective('stale-if-error'); $ttl += $stale == true ? $ttl : $stale; } // Determine which manifest key should be used $key = $this->getCacheKey($request); $persistedRequest = $this->persistHeaders($request); $entries = array(); if ($manifest = $this->cache->fetch($key)) { // Determine which cache entries should still be in the cache $vary = $response->getVary(); foreach (unserialize($manifest) as $entry) { // Check if the entry is expired if ($entry[4] < $currentTime) { continue; } $entry[1]['vary'] = isset($entry[1]['vary']) ? $entry[1]['vary'] : ''; if ($vary != $entry[1]['vary'] || !$this->requestsMatch($vary, $entry[0], $persistedRequest)) { $entries[] = $entry; } } } // Persist the response body if needed $bodyDigest = null; if ($response->getBody() && $response->getBody()->getContentLength() > 0) { $bodyDigest = $this->getBodyKey($request->getUrl(), $response->getBody()); $this->cache->save($bodyDigest, (string) $response->getBody(), $ttl); } array_unshift($entries, array($persistedRequest, $this->persistHeaders($response), $response->getStatusCode(), $bodyDigest, $currentTime + $ttl)); $this->cache->save($key, serialize($entries)); }