/** * Check if an already cached request must be revalidated, and if so update * the request with the correct ETag headers. * @param HttpRequest $cached A previously cached response. * @param HttpRequest $request The outbound request. * return bool If the cached object needs to be revalidated, false if it is * still current and can be re-used. */ protected function checkMustRevaliadateCachedRequest($cached, $request) { if (Google_CacheParser::mustRevalidate($cached)) { $addHeaders = array(); if ($cached->getResponseHeader('etag')) { // [13.3.4] If an entity tag has been provided by the origin server, // we must use that entity tag in any cache-conditional request. $addHeaders['If-None-Match'] = $cached->getResponseHeader('etag'); } elseif ($cached->getResponseHeader('date')) { $addHeaders['If-Modified-Since'] = $cached->getResponseHeader('date'); } $request->setRequestHeaders($addHeaders); return true; } else { return false; } }
/** * @visible for testing. * @param Google_HttpRequest $request * @return Google_HttpRequest|bool Returns the cached object or * false if the operation was unsuccessful. */ public function getCachedRequest(Google_HttpRequest $request) { if (false == Google_CacheParser::isRequestCacheable($request)) { false; } return Google_Client::$cache->get($request->getCacheKey()); }
public function testMustRevalidate() { $now = time(); // Expires 1 year in the future, and contains the must-revalidate directive. // Don't revalidate. must-revalidate only applies to expired entries. $future = $now + 365 * 24 * 60 * 60; $resp = new Google_HttpRequest('http://localhost', 'GET'); $resp->setResponseHttpCode('200'); $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600, must-revalidate', 'Expires' => gmdate('D, d M Y H:i:s', $future) . ' GMT', 'Date' => gmdate('D, d M Y H:i:s', $now) . ' GMT')); $this->assertFalse(Google_CacheParser::mustRevalidate($resp)); // Contains the max-age=3600 directive, but was created 2 hours ago. // Must revalidate. $past = $now - 2 * 60 * 60; $resp = new Google_HttpRequest('http://localhost', 'GET'); $resp->setResponseHttpCode('200'); $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600', 'Expires' => gmdate('D, d M Y H:i:s', $future) . ' GMT', 'Date' => gmdate('D, d M Y H:i:s', $past) . ' GMT')); $this->assertTrue(Google_CacheParser::mustRevalidate($resp)); // Contains the max-age=3600 directive, and was created 600 seconds ago. // No need to revalidate, regardless of the expires header. $past = $now - 600; $resp = new Google_HttpRequest('http://localhost', 'GET'); $resp->setResponseHttpCode('200'); $resp->setResponseHeaders(array('Cache-Control' => 'max-age=3600', 'Expires' => gmdate('D, d M Y H:i:s', $past) . ' GMT', 'Date' => gmdate('D, d M Y H:i:s', $past) . ' GMT')); $this->assertFalse(Google_CacheParser::mustRevalidate($resp)); }