/**
* Store a response generated by a request.
*
* @param Request $request
* @param Response $response
* @param integer $ttl
*/
public function cache(Request $request, Response $response, $ttl = null)
{
// only cache GET and HEAD requests
if (!in_array($request->getMethod(), array('GET', 'HEAD'))) {
return;
}
// respect Cache-Control: no-cache
if ($request->isNoCache()) {
return;
}
// skip already cached response
if ($response->headers->has('X-ServerCache-Key')) {
return;
}
// set cache lifetime
if (is_null($ttl)) {
$ttl = $this->defaultTtl;
}
$expirationDate = date_create('NOW + ' . $ttl . ' seconds');
// save cache item
$key = $this->getCacheKey($request);
$metadataReponse = new MetadataResponse($response, array("expirationDate" => $expirationDate));
$item = new CacheItem($key, true, $metadataReponse);
$item->expiresAt($expirationDate);
$this->cache->save($item);
}