Skip to content

Commit

Permalink
Clean up, move re-validation adding to a method
Browse files Browse the repository at this point in the history
  • Loading branch information
Kevinrob committed Jul 16, 2015
1 parent 76ab442 commit 865528a
Showing 1 changed file with 35 additions and 17 deletions.
52 changes: 35 additions & 17 deletions src/CacheMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,23 +75,7 @@ public static function getMiddleware(CacheStorageInterface $cacheStorage = null)
$request = static::getRequestWithReValidationHeader($request, $cacheEntry);

if ($cacheEntry->staleWhileValidate()) {
// Add the promise for revalidate
if (static::$client !== null) {
/** @var RequestInterface $reValidationRequest */
$reValidationRequest = $request->withHeader("X-ReValidation", "1");
static::$waitingRevalidate[] = static::$client
->sendAsync($reValidationRequest)
->then(function (ResponseInterface $response) use ($request, &$cacheStorage, $cacheEntry) {
if ($response->getStatusCode() == 304) {
// Not modified => cache entry is re-validate
/** @var ResponseInterface $response */
$response = $response->withStatus($cacheEntry->getResponse()->getStatusCode());
$response = $response->withBody($cacheEntry->getResponse()->getBody());
}

$cacheStorage->cache($request, $response);
});
}
static::addReValidationRequest($request, $cacheStorage, $cacheEntry);

return new FulfilledPromise(
$cacheEntry->getResponse()
Expand Down Expand Up @@ -180,4 +164,38 @@ protected static function getRequestWithReValidationHeader(RequestInterface $req
return $request;
}

/**
* @param RequestInterface $request
* @param CacheStorageInterface $cacheStorage
* @param CacheEntry $cacheEntry
* @return bool if added
*/
protected static function addReValidationRequest(
RequestInterface $request,
CacheStorageInterface &$cacheStorage,
CacheEntry $cacheEntry
) {
// Add the promise for revalidate
if (static::$client !== null) {
/** @var RequestInterface $request */
$request = $request->withHeader("X-ReValidation", "1");
static::$waitingRevalidate[] = static::$client
->sendAsync($request)
->then(function (ResponseInterface $response) use ($request, &$cacheStorage, $cacheEntry) {
if ($response->getStatusCode() == 304) {
// Not modified => cache entry is re-validate
/** @var ResponseInterface $response */
$response = $response->withStatus($cacheEntry->getResponse()->getStatusCode());
$response = $response->withBody($cacheEntry->getResponse()->getBody());
}

$cacheStorage->cache($request, $response);
});

return true;
}

return false;
}

}

0 comments on commit 865528a

Please sign in to comment.