updated backend
This commit is contained in:
parent
1fea0f4fe7
commit
11521c2339
3459 changed files with 72735 additions and 168535 deletions
|
|
@ -24,16 +24,16 @@ use Symfony\Component\HttpKernel\HttpKernelInterface;
|
|||
abstract class AbstractSurrogate implements SurrogateInterface
|
||||
{
|
||||
protected $contentTypes;
|
||||
protected $phpEscapeMap = array(
|
||||
array('<?', '<%', '<s', '<S'),
|
||||
array('<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'),
|
||||
);
|
||||
protected $phpEscapeMap = [
|
||||
['<?', '<%', '<s', '<S'],
|
||||
['<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'],
|
||||
];
|
||||
|
||||
/**
|
||||
* @param array $contentTypes An array of content-type that should be parsed for Surrogate information
|
||||
* (default: text/html, text/xml, application/xhtml+xml, and application/xml)
|
||||
*/
|
||||
public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'))
|
||||
public function __construct(array $contentTypes = ['text/html', 'text/xml', 'application/xhtml+xml', 'application/xml'])
|
||||
{
|
||||
$this->contentTypes = $contentTypes;
|
||||
}
|
||||
|
|
@ -90,7 +90,7 @@ abstract class AbstractSurrogate implements SurrogateInterface
|
|||
*/
|
||||
public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
|
||||
{
|
||||
$subRequest = Request::create($uri, Request::METHOD_GET, array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all());
|
||||
$subRequest = Request::create($uri, Request::METHOD_GET, [], $cache->getRequest()->cookies->all(), [], $cache->getRequest()->server->all());
|
||||
|
||||
try {
|
||||
$response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
|
||||
|
|
@ -109,6 +109,8 @@ abstract class AbstractSurrogate implements SurrogateInterface
|
|||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -85,7 +85,7 @@ class Esi extends AbstractSurrogate
|
|||
|
||||
$i = 1;
|
||||
while (isset($chunks[$i])) {
|
||||
$options = array();
|
||||
$options = [];
|
||||
preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
|
||||
foreach ($matches as $set) {
|
||||
$options[$set[1]] = $set[2];
|
||||
|
|
@ -111,5 +111,7 @@ class Esi extends AbstractSurrogate
|
|||
|
||||
// remove ESI/1.0 from the Surrogate-Control header
|
||||
$this->removeFromControl($response);
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -32,15 +32,22 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
private $request;
|
||||
private $surrogate;
|
||||
private $surrogateCacheStrategy;
|
||||
private $options = array();
|
||||
private $traces = array();
|
||||
private $options = [];
|
||||
private $traces = [];
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* The available options are:
|
||||
*
|
||||
* * debug: If true, the traces are added as a HTTP header to ease debugging
|
||||
* * debug If true, exceptions are thrown when things go wrong. Otherwise, the cache
|
||||
* will try to carry on and deliver a meaningful response.
|
||||
*
|
||||
* * trace_level May be one of 'none', 'short' and 'full'. For 'short', a concise trace of the
|
||||
* master request will be added as an HTTP header. 'full' will add traces for all
|
||||
* requests (including ESI subrequests). (default: 'full' if in debug; 'none' otherwise)
|
||||
*
|
||||
* * trace_header Header name to use for traces. (default: X-Symfony-Cache)
|
||||
*
|
||||
* * default_ttl The number of seconds that a cache entry should be considered
|
||||
* fresh when no explicit freshness information is provided in
|
||||
|
|
@ -70,30 +77,36 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
* This setting is overridden by the stale-if-error HTTP Cache-Control extension
|
||||
* (see RFC 5861).
|
||||
*/
|
||||
public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = array())
|
||||
public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = [])
|
||||
{
|
||||
$this->store = $store;
|
||||
$this->kernel = $kernel;
|
||||
$this->surrogate = $surrogate;
|
||||
|
||||
// needed in case there is a fatal error because the backend is too slow to respond
|
||||
register_shutdown_function(array($this->store, 'cleanup'));
|
||||
register_shutdown_function([$this->store, 'cleanup']);
|
||||
|
||||
$this->options = array_merge(array(
|
||||
$this->options = array_merge([
|
||||
'debug' => false,
|
||||
'default_ttl' => 0,
|
||||
'private_headers' => array('Authorization', 'Cookie'),
|
||||
'private_headers' => ['Authorization', 'Cookie'],
|
||||
'allow_reload' => false,
|
||||
'allow_revalidate' => false,
|
||||
'stale_while_revalidate' => 2,
|
||||
'stale_if_error' => 60,
|
||||
), $options);
|
||||
'trace_level' => 'none',
|
||||
'trace_header' => 'X-Symfony-Cache',
|
||||
], $options);
|
||||
|
||||
if (!isset($options['trace_level'])) {
|
||||
$this->options['trace_level'] = $this->options['debug'] ? 'full' : 'none';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current store.
|
||||
*
|
||||
* @return StoreInterface $store A StoreInterface instance
|
||||
* @return StoreInterface A StoreInterface instance
|
||||
*/
|
||||
public function getStore()
|
||||
{
|
||||
|
|
@ -110,6 +123,23 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
return $this->traces;
|
||||
}
|
||||
|
||||
private function addTraces(Response $response)
|
||||
{
|
||||
$traceString = null;
|
||||
|
||||
if ('full' === $this->options['trace_level']) {
|
||||
$traceString = $this->getLog();
|
||||
}
|
||||
|
||||
if ('short' === $this->options['trace_level'] && $masterId = array_key_first($this->traces)) {
|
||||
$traceString = implode('/', $this->traces[$masterId]);
|
||||
}
|
||||
|
||||
if (null !== $traceString) {
|
||||
$response->headers->add([$this->options['trace_header'] => $traceString]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a log message for the events of the last request processing.
|
||||
*
|
||||
|
|
@ -117,7 +147,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
*/
|
||||
public function getLog()
|
||||
{
|
||||
$log = array();
|
||||
$log = [];
|
||||
foreach ($this->traces as $request => $traces) {
|
||||
$log[] = sprintf('%s: %s', $request, implode(', ', $traces));
|
||||
}
|
||||
|
|
@ -164,7 +194,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
{
|
||||
// FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism
|
||||
if (HttpKernelInterface::MASTER_REQUEST === $type) {
|
||||
$this->traces = array();
|
||||
$this->traces = [];
|
||||
// Keep a clone of the original request for surrogates so they can access it.
|
||||
// We must clone here to get a separate instance because the application will modify the request during
|
||||
// the application flow (we know it always does because we do ourselves by setting REMOTE_ADDR to 127.0.0.1
|
||||
|
|
@ -175,9 +205,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
}
|
||||
}
|
||||
|
||||
$this->traces[$this->getTraceKey($request)] = array();
|
||||
$this->traces[$this->getTraceKey($request)] = [];
|
||||
|
||||
if (!$request->isMethodSafe(false)) {
|
||||
if (!$request->isMethodSafe()) {
|
||||
$response = $this->invalidate($request, $catch);
|
||||
} elseif ($request->headers->has('expect') || !$request->isMethodCacheable()) {
|
||||
$response = $this->pass($request, $catch);
|
||||
|
|
@ -194,8 +224,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
|
||||
$this->restoreResponseBody($request, $response);
|
||||
|
||||
if (HttpKernelInterface::MASTER_REQUEST === $type && $this->options['debug']) {
|
||||
$response->headers->set('X-Symfony-Cache', $this->getLog());
|
||||
if (HttpKernelInterface::MASTER_REQUEST === $type) {
|
||||
$this->addTraces($response);
|
||||
}
|
||||
|
||||
if (null !== $this->surrogate) {
|
||||
|
|
@ -226,8 +256,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
/**
|
||||
* Forwards the Request to the backend without storing the Response in the cache.
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
* @param bool $catch Whether to process exceptions
|
||||
* @param bool $catch Whether to process exceptions
|
||||
*
|
||||
* @return Response A Response instance
|
||||
*/
|
||||
|
|
@ -241,8 +270,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
/**
|
||||
* Invalidates non-safe methods (like POST, PUT, and DELETE).
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
* @param bool $catch Whether to process exceptions
|
||||
* @param bool $catch Whether to process exceptions
|
||||
*
|
||||
* @return Response A Response instance
|
||||
*
|
||||
|
|
@ -260,9 +288,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
$this->store->invalidate($request);
|
||||
|
||||
// As per the RFC, invalidate Location and Content-Location URLs if present
|
||||
foreach (array('Location', 'Content-Location') as $header) {
|
||||
foreach (['Location', 'Content-Location'] as $header) {
|
||||
if ($uri = $response->headers->get($header)) {
|
||||
$subRequest = Request::create($uri, 'get', array(), array(), array(), $request->server->all());
|
||||
$subRequest = Request::create($uri, 'get', [], [], [], $request->server->all());
|
||||
|
||||
$this->store->invalidate($subRequest);
|
||||
}
|
||||
|
|
@ -290,8 +318,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
* the backend using conditional GET. When no matching cache entry is found,
|
||||
* it triggers "miss" processing.
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
* @param bool $catch Whether to process exceptions
|
||||
* @param bool $catch Whether to process exceptions
|
||||
*
|
||||
* @return Response A Response instance
|
||||
*
|
||||
|
|
@ -336,9 +363,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
* The original request is used as a template for a conditional
|
||||
* GET request with the backend.
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
* @param Response $entry A Response instance to validate
|
||||
* @param bool $catch Whether to process exceptions
|
||||
* @param bool $catch Whether to process exceptions
|
||||
*
|
||||
* @return Response A Response instance
|
||||
*/
|
||||
|
|
@ -352,12 +377,14 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
}
|
||||
|
||||
// add our cached last-modified validator
|
||||
$subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
|
||||
if ($entry->headers->has('Last-Modified')) {
|
||||
$subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
|
||||
}
|
||||
|
||||
// Add our cached etag validator to the environment.
|
||||
// We keep the etags from the client to handle the case when the client
|
||||
// has a different private valid entry which is not cached here.
|
||||
$cachedEtags = $entry->getEtag() ? array($entry->getEtag()) : array();
|
||||
$cachedEtags = $entry->getEtag() ? [$entry->getEtag()] : [];
|
||||
$requestEtags = $request->getETags();
|
||||
if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) {
|
||||
$subRequest->headers->set('if_none_match', implode(', ', $etags));
|
||||
|
|
@ -377,7 +404,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
$entry = clone $entry;
|
||||
$entry->headers->remove('Date');
|
||||
|
||||
foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) {
|
||||
foreach (['Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified'] as $name) {
|
||||
if ($response->headers->has($name)) {
|
||||
$entry->headers->set($name, $response->headers->get($name));
|
||||
}
|
||||
|
|
@ -399,8 +426,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
* Unconditionally fetches a fresh response from the backend and
|
||||
* stores it in the cache if is cacheable.
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
* @param bool $catch Whether to process exceptions
|
||||
* @param bool $catch Whether to process exceptions
|
||||
*
|
||||
* @return Response A Response instance
|
||||
*/
|
||||
|
|
@ -432,9 +458,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
* All backend requests (cache passes, fetches, cache validations)
|
||||
* run through this method.
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
* @param bool $catch Whether to catch exceptions or not
|
||||
* @param Response $entry A Response instance (the stale entry if present, null otherwise)
|
||||
* @param bool $catch Whether to catch exceptions or not
|
||||
* @param Response|null $entry A Response instance (the stale entry if present, null otherwise)
|
||||
*
|
||||
* @return Response A Response instance
|
||||
*/
|
||||
|
|
@ -448,7 +473,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
$response = SubRequestHandler::handle($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST, $catch);
|
||||
|
||||
// we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC
|
||||
if (null !== $entry && \in_array($response->getStatusCode(), array(500, 502, 503, 504))) {
|
||||
if (null !== $entry && \in_array($response->getStatusCode(), [500, 502, 503, 504])) {
|
||||
if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
|
||||
$age = $this->options['stale_if_error'];
|
||||
}
|
||||
|
|
@ -612,10 +637,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
/**
|
||||
* Checks if the Request includes authorization or other sensitive information
|
||||
* that should cause the Response to be considered private by default.
|
||||
*
|
||||
* @return bool true if the Request is private, false otherwise
|
||||
*/
|
||||
private function isPrivateRequest(Request $request)
|
||||
private function isPrivateRequest(Request $request): bool
|
||||
{
|
||||
foreach ($this->options['private_headers'] as $key) {
|
||||
$key = strtolower(str_replace('HTTP_', '', $key));
|
||||
|
|
@ -634,23 +657,16 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
|
||||
/**
|
||||
* Records that an event took place.
|
||||
*
|
||||
* @param Request $request A Request instance
|
||||
* @param string $event The event name
|
||||
*/
|
||||
private function record(Request $request, $event)
|
||||
private function record(Request $request, string $event)
|
||||
{
|
||||
$this->traces[$this->getTraceKey($request)][] = $event;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the key we use in the "trace" array for a given request.
|
||||
*
|
||||
* @param Request $request
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function getTraceKey(Request $request)
|
||||
private function getTraceKey(Request $request): string
|
||||
{
|
||||
$path = $request->getPathInfo();
|
||||
if ($qs = $request->getQueryString()) {
|
||||
|
|
@ -663,12 +679,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
/**
|
||||
* Checks whether the given (cached) response may be served as "stale" when a revalidation
|
||||
* is currently in progress.
|
||||
*
|
||||
* @param Response $entry
|
||||
*
|
||||
* @return bool true when the stale response may be served, false otherwise
|
||||
*/
|
||||
private function mayServeStaleWhileRevalidate(Response $entry)
|
||||
private function mayServeStaleWhileRevalidate(Response $entry): bool
|
||||
{
|
||||
$timeout = $entry->headers->getCacheControlDirective('stale-while-revalidate');
|
||||
|
||||
|
|
@ -681,12 +693,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
|
|||
|
||||
/**
|
||||
* Waits for the store to release a locked entry.
|
||||
*
|
||||
* @param Request $request The request to wait for
|
||||
*
|
||||
* @return bool true if the lock was released before the internal timeout was hit; false if the wait timeout was exceeded
|
||||
*/
|
||||
private function waitForLock(Request $request)
|
||||
private function waitForLock(Request $request): bool
|
||||
{
|
||||
$wait = 0;
|
||||
while ($this->store->isLocked($request) && $wait < 100) {
|
||||
|
|
|
|||
|
|
@ -5,10 +5,6 @@
|
|||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* This code is partially based on the Rack-Cache library by Ryan Tomayko,
|
||||
* which is released under the MIT license.
|
||||
* (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801)
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
|
@ -28,30 +24,69 @@ use Symfony\Component\HttpFoundation\Response;
|
|||
*/
|
||||
class ResponseCacheStrategy implements ResponseCacheStrategyInterface
|
||||
{
|
||||
private $cacheable = true;
|
||||
/**
|
||||
* Cache-Control headers that are sent to the final response if they appear in ANY of the responses.
|
||||
*/
|
||||
private static $overrideDirectives = ['private', 'no-cache', 'no-store', 'no-transform', 'must-revalidate', 'proxy-revalidate'];
|
||||
|
||||
/**
|
||||
* Cache-Control headers that are sent to the final response if they appear in ALL of the responses.
|
||||
*/
|
||||
private static $inheritDirectives = ['public', 'immutable'];
|
||||
|
||||
private $embeddedResponses = 0;
|
||||
private $ttls = array();
|
||||
private $maxAges = array();
|
||||
private $isNotCacheableResponseEmbedded = false;
|
||||
private $age = 0;
|
||||
private $flagDirectives = [
|
||||
'no-cache' => null,
|
||||
'no-store' => null,
|
||||
'no-transform' => null,
|
||||
'must-revalidate' => null,
|
||||
'proxy-revalidate' => null,
|
||||
'public' => null,
|
||||
'private' => null,
|
||||
'immutable' => null,
|
||||
];
|
||||
private $ageDirectives = [
|
||||
'max-age' => null,
|
||||
's-maxage' => null,
|
||||
'expires' => null,
|
||||
];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function add(Response $response)
|
||||
{
|
||||
if (!$response->isFresh() || !$response->isCacheable()) {
|
||||
$this->cacheable = false;
|
||||
} else {
|
||||
$maxAge = $response->getMaxAge();
|
||||
$this->ttls[] = $response->getTtl();
|
||||
$this->maxAges[] = $maxAge;
|
||||
++$this->embeddedResponses;
|
||||
|
||||
if (null === $maxAge) {
|
||||
$this->isNotCacheableResponseEmbedded = true;
|
||||
foreach (self::$overrideDirectives as $directive) {
|
||||
if ($response->headers->hasCacheControlDirective($directive)) {
|
||||
$this->flagDirectives[$directive] = true;
|
||||
}
|
||||
}
|
||||
|
||||
++$this->embeddedResponses;
|
||||
foreach (self::$inheritDirectives as $directive) {
|
||||
if (false !== $this->flagDirectives[$directive]) {
|
||||
$this->flagDirectives[$directive] = $response->headers->hasCacheControlDirective($directive);
|
||||
}
|
||||
}
|
||||
|
||||
$age = $response->getAge();
|
||||
$this->age = max($this->age, $age);
|
||||
|
||||
if ($this->willMakeFinalResponseUncacheable($response)) {
|
||||
$this->isNotCacheableResponseEmbedded = true;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->storeRelativeAgeDirective('max-age', $response->headers->getCacheControlDirective('max-age'), $age);
|
||||
$this->storeRelativeAgeDirective('s-maxage', $response->headers->getCacheControlDirective('s-maxage') ?: $response->headers->getCacheControlDirective('max-age'), $age);
|
||||
|
||||
$expires = $response->getExpires();
|
||||
$expires = null !== $expires ? (int) $expires->format('U') - (int) $response->getDate()->format('U') : null;
|
||||
$this->storeRelativeAgeDirective('expires', $expires >= 0 ? $expires : null, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -64,33 +99,115 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
|
|||
return;
|
||||
}
|
||||
|
||||
// Remove validation related headers in order to avoid browsers using
|
||||
// their own cache, because some of the response content comes from
|
||||
// at least one embedded response (which likely has a different caching strategy).
|
||||
if ($response->isValidateable()) {
|
||||
$response->setEtag(null);
|
||||
$response->setLastModified(null);
|
||||
}
|
||||
// Remove validation related headers of the master response,
|
||||
// because some of the response content comes from at least
|
||||
// one embedded response (which likely has a different caching strategy).
|
||||
$response->setEtag(null);
|
||||
$response->setLastModified(null);
|
||||
|
||||
if (!$response->isFresh() || !$response->isCacheable()) {
|
||||
$this->cacheable = false;
|
||||
}
|
||||
$this->add($response);
|
||||
|
||||
if (!$this->cacheable) {
|
||||
$response->headers->set('Cache-Control', 'no-cache, must-revalidate');
|
||||
$response->headers->set('Age', $this->age);
|
||||
|
||||
if ($this->isNotCacheableResponseEmbedded) {
|
||||
if ($this->flagDirectives['no-store']) {
|
||||
$response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');
|
||||
} else {
|
||||
$response->headers->set('Cache-Control', 'no-cache, must-revalidate');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->ttls[] = $response->getTtl();
|
||||
$this->maxAges[] = $response->getMaxAge();
|
||||
$flags = array_filter($this->flagDirectives);
|
||||
|
||||
if ($this->isNotCacheableResponseEmbedded) {
|
||||
$response->headers->removeCacheControlDirective('s-maxage');
|
||||
} elseif (null !== $maxAge = min($this->maxAges)) {
|
||||
$response->setSharedMaxAge($maxAge);
|
||||
$response->headers->set('Age', $maxAge - min($this->ttls));
|
||||
if (isset($flags['must-revalidate'])) {
|
||||
$flags['no-cache'] = true;
|
||||
}
|
||||
|
||||
$response->headers->set('Cache-Control', implode(', ', array_keys($flags)));
|
||||
|
||||
$maxAge = null;
|
||||
|
||||
if (is_numeric($this->ageDirectives['max-age'])) {
|
||||
$maxAge = $this->ageDirectives['max-age'] + $this->age;
|
||||
$response->headers->addCacheControlDirective('max-age', $maxAge);
|
||||
}
|
||||
|
||||
if (is_numeric($this->ageDirectives['s-maxage'])) {
|
||||
$sMaxage = $this->ageDirectives['s-maxage'] + $this->age;
|
||||
|
||||
if ($maxAge !== $sMaxage) {
|
||||
$response->headers->addCacheControlDirective('s-maxage', $sMaxage);
|
||||
}
|
||||
}
|
||||
|
||||
if (is_numeric($this->ageDirectives['expires'])) {
|
||||
$date = clone $response->getDate();
|
||||
$date->modify('+'.($this->ageDirectives['expires'] + $this->age).' seconds');
|
||||
$response->setExpires($date);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* RFC2616, Section 13.4.
|
||||
*
|
||||
* @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
|
||||
*/
|
||||
private function willMakeFinalResponseUncacheable(Response $response): bool
|
||||
{
|
||||
// RFC2616: A response received with a status code of 200, 203, 300, 301 or 410
|
||||
// MAY be stored by a cache […] unless a cache-control directive prohibits caching.
|
||||
if ($response->headers->hasCacheControlDirective('no-cache')
|
||||
|| $response->headers->getCacheControlDirective('no-store')
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Last-Modified and Etag headers cannot be merged, they render the response uncacheable
|
||||
// by default (except if the response also has max-age etc.).
|
||||
if (\in_array($response->getStatusCode(), [200, 203, 300, 301, 410])
|
||||
&& null === $response->getLastModified()
|
||||
&& null === $response->getEtag()
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// RFC2616: A response received with any other status code (e.g. status codes 302 and 307)
|
||||
// MUST NOT be returned in a reply to a subsequent request unless there are
|
||||
// cache-control directives or another header(s) that explicitly allow it.
|
||||
$cacheControl = ['max-age', 's-maxage', 'must-revalidate', 'proxy-revalidate', 'public', 'private'];
|
||||
foreach ($cacheControl as $key) {
|
||||
if ($response->headers->hasCacheControlDirective($key)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if ($response->headers->has('Expires')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Store lowest max-age/s-maxage/expires for the final response.
|
||||
*
|
||||
* The response might have been stored in cache a while ago. To keep things comparable,
|
||||
* we have to subtract the age so that the value is normalized for an age of 0.
|
||||
*
|
||||
* If the value is lower than the currently stored value, we update the value, to keep a rolling
|
||||
* minimal value of each instruction. If the value is NULL, the directive will not be set on the final response.
|
||||
*/
|
||||
private function storeRelativeAgeDirective(string $directive, ?int $value, int $age)
|
||||
{
|
||||
if (null === $value) {
|
||||
$this->ageDirectives[$directive] = false;
|
||||
}
|
||||
|
||||
if (false !== $this->ageDirectives[$directive]) {
|
||||
$value -= $age;
|
||||
$this->ageDirectives[$directive] = null !== $this->ageDirectives[$directive] ? min($this->ageDirectives[$directive], $value) : $value;
|
||||
}
|
||||
$response->setMaxAge(0);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -70,7 +70,7 @@ class Ssi extends AbstractSurrogate
|
|||
|
||||
$i = 1;
|
||||
while (isset($chunks[$i])) {
|
||||
$options = array();
|
||||
$options = [];
|
||||
preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
|
||||
foreach ($matches as $set) {
|
||||
$options[$set[1]] = $set[2];
|
||||
|
|
@ -94,5 +94,7 @@ class Ssi extends AbstractSurrogate
|
|||
|
||||
// remove SSI/1.0 from the Surrogate-Control header
|
||||
$this->removeFromControl($response);
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -29,18 +29,16 @@ class Store implements StoreInterface
|
|||
private $locks;
|
||||
|
||||
/**
|
||||
* @param string $root The path to the cache directory
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
*/
|
||||
public function __construct($root)
|
||||
public function __construct(string $root)
|
||||
{
|
||||
$this->root = $root;
|
||||
if (!file_exists($this->root) && !@mkdir($this->root, 0777, true) && !is_dir($this->root)) {
|
||||
throw new \RuntimeException(sprintf('Unable to create the store directory (%s).', $this->root));
|
||||
}
|
||||
$this->keyCache = new \SplObjectStorage();
|
||||
$this->locks = array();
|
||||
$this->locks = [];
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -54,7 +52,7 @@ class Store implements StoreInterface
|
|||
fclose($lock);
|
||||
}
|
||||
|
||||
$this->locks = array();
|
||||
$this->locks = [];
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -134,7 +132,7 @@ class Store implements StoreInterface
|
|||
$key = $this->getCacheKey($request);
|
||||
|
||||
if (!$entries = $this->getMetadata($key)) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
// find a cached entry that matches the request.
|
||||
|
|
@ -148,7 +146,7 @@ class Store implements StoreInterface
|
|||
}
|
||||
|
||||
if (null === $match) {
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
|
||||
$headers = $match[1];
|
||||
|
|
@ -159,6 +157,7 @@ class Store implements StoreInterface
|
|||
// TODO the metaStore referenced an entity that doesn't exist in
|
||||
// the entityStore. We definitely want to return nil but we should
|
||||
// also purge the entry from the meta-store when this is detected.
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -180,7 +179,7 @@ class Store implements StoreInterface
|
|||
if (!$response->headers->has('X-Content-Digest')) {
|
||||
$digest = $this->generateContentDigest($response);
|
||||
|
||||
if (false === $this->save($digest, $response->getContent())) {
|
||||
if (!$this->save($digest, $response->getContent())) {
|
||||
throw new \RuntimeException('Unable to store the entity.');
|
||||
}
|
||||
|
||||
|
|
@ -192,11 +191,11 @@ class Store implements StoreInterface
|
|||
}
|
||||
|
||||
// read existing cache entries, remove non-varying, and add this one to the list
|
||||
$entries = array();
|
||||
$entries = [];
|
||||
$vary = $response->headers->get('vary');
|
||||
foreach ($this->getMetadata($key) as $entry) {
|
||||
if (!isset($entry[1]['vary'][0])) {
|
||||
$entry[1]['vary'] = array('');
|
||||
$entry[1]['vary'] = [''];
|
||||
}
|
||||
|
||||
if ($entry[1]['vary'][0] != $vary || !$this->requestsMatch($vary, $entry[0], $storedEnv)) {
|
||||
|
|
@ -207,9 +206,9 @@ class Store implements StoreInterface
|
|||
$headers = $this->persistResponse($response);
|
||||
unset($headers['age']);
|
||||
|
||||
array_unshift($entries, array($storedEnv, $headers));
|
||||
array_unshift($entries, [$storedEnv, $headers]);
|
||||
|
||||
if (false === $this->save($key, serialize($entries))) {
|
||||
if (!$this->save($key, serialize($entries))) {
|
||||
throw new \RuntimeException('Unable to store the metadata.');
|
||||
}
|
||||
|
||||
|
|
@ -236,19 +235,19 @@ class Store implements StoreInterface
|
|||
$modified = false;
|
||||
$key = $this->getCacheKey($request);
|
||||
|
||||
$entries = array();
|
||||
$entries = [];
|
||||
foreach ($this->getMetadata($key) as $entry) {
|
||||
$response = $this->restoreResponse($entry[1]);
|
||||
if ($response->isFresh()) {
|
||||
$response->expire();
|
||||
$modified = true;
|
||||
$entries[] = array($entry[0], $this->persistResponse($response));
|
||||
$entries[] = [$entry[0], $this->persistResponse($response)];
|
||||
} else {
|
||||
$entries[] = $entry;
|
||||
}
|
||||
}
|
||||
|
||||
if ($modified && false === $this->save($key, serialize($entries))) {
|
||||
if ($modified && !$this->save($key, serialize($entries))) {
|
||||
throw new \RuntimeException('Unable to store the metadata.');
|
||||
}
|
||||
}
|
||||
|
|
@ -260,10 +259,8 @@ class Store implements StoreInterface
|
|||
* @param string $vary A Response vary header
|
||||
* @param array $env1 A Request HTTP header array
|
||||
* @param array $env2 A Request HTTP header array
|
||||
*
|
||||
* @return bool true if the two environments match, false otherwise
|
||||
*/
|
||||
private function requestsMatch($vary, $env1, $env2)
|
||||
private function requestsMatch(?string $vary, array $env1, array $env2): bool
|
||||
{
|
||||
if (empty($vary)) {
|
||||
return true;
|
||||
|
|
@ -285,15 +282,11 @@ class Store implements StoreInterface
|
|||
* Gets all data associated with the given key.
|
||||
*
|
||||
* Use this method only if you know what you are doing.
|
||||
*
|
||||
* @param string $key The store key
|
||||
*
|
||||
* @return array An array of data associated with the key
|
||||
*/
|
||||
private function getMetadata($key)
|
||||
private function getMetadata(string $key): array
|
||||
{
|
||||
if (!$entries = $this->load($key)) {
|
||||
return array();
|
||||
return [];
|
||||
}
|
||||
|
||||
return unserialize($entries);
|
||||
|
|
@ -321,12 +314,8 @@ class Store implements StoreInterface
|
|||
|
||||
/**
|
||||
* Purges data for the given URL.
|
||||
*
|
||||
* @param string $url A URL
|
||||
*
|
||||
* @return bool true if the URL exists and has been purged, false otherwise
|
||||
*/
|
||||
private function doPurge($url)
|
||||
private function doPurge(string $url): bool
|
||||
{
|
||||
$key = $this->getCacheKey(Request::create($url));
|
||||
if (isset($this->locks[$key])) {
|
||||
|
|
@ -346,27 +335,18 @@ class Store implements StoreInterface
|
|||
|
||||
/**
|
||||
* Loads data for the given key.
|
||||
*
|
||||
* @param string $key The store key
|
||||
*
|
||||
* @return string The data associated with the key
|
||||
*/
|
||||
private function load($key)
|
||||
private function load(string $key): ?string
|
||||
{
|
||||
$path = $this->getPath($key);
|
||||
|
||||
return file_exists($path) ? file_get_contents($path) : false;
|
||||
return file_exists($path) && false !== ($contents = file_get_contents($path)) ? $contents : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save data for the given key.
|
||||
*
|
||||
* @param string $key The store key
|
||||
* @param string $data The data to store
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function save($key, $data)
|
||||
private function save(string $key, string $data): bool
|
||||
{
|
||||
$path = $this->getPath($key);
|
||||
|
||||
|
|
@ -408,6 +388,8 @@ class Store implements StoreInterface
|
|||
}
|
||||
|
||||
@chmod($path, 0666 & ~umask());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function getPath($key)
|
||||
|
|
@ -434,10 +416,8 @@ class Store implements StoreInterface
|
|||
|
||||
/**
|
||||
* Returns a cache key for the given Request.
|
||||
*
|
||||
* @return string A key for the given Request
|
||||
*/
|
||||
private function getCacheKey(Request $request)
|
||||
private function getCacheKey(Request $request): string
|
||||
{
|
||||
if (isset($this->keyCache[$request])) {
|
||||
return $this->keyCache[$request];
|
||||
|
|
@ -448,42 +428,33 @@ class Store implements StoreInterface
|
|||
|
||||
/**
|
||||
* Persists the Request HTTP headers.
|
||||
*
|
||||
* @return array An array of HTTP headers
|
||||
*/
|
||||
private function persistRequest(Request $request)
|
||||
private function persistRequest(Request $request): array
|
||||
{
|
||||
return $request->headers->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Persists the Response HTTP headers.
|
||||
*
|
||||
* @return array An array of HTTP headers
|
||||
*/
|
||||
private function persistResponse(Response $response)
|
||||
private function persistResponse(Response $response): array
|
||||
{
|
||||
$headers = $response->headers->all();
|
||||
$headers['X-Status'] = array($response->getStatusCode());
|
||||
$headers['X-Status'] = [$response->getStatusCode()];
|
||||
|
||||
return $headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restores a Response from the HTTP headers and body.
|
||||
*
|
||||
* @param array $headers An array of HTTP headers for the Response
|
||||
* @param string $body The Response body
|
||||
*
|
||||
* @return Response
|
||||
*/
|
||||
private function restoreResponse($headers, $body = null)
|
||||
private function restoreResponse(array $headers, string $body = null): Response
|
||||
{
|
||||
$status = $headers['X-Status'][0];
|
||||
unset($headers['X-Status']);
|
||||
|
||||
if (null !== $body) {
|
||||
$headers['X-Body-File'] = array($body);
|
||||
$headers['X-Body-File'] = [$body];
|
||||
}
|
||||
|
||||
return new Response($body, $status, $headers);
|
||||
|
|
|
|||
|
|
@ -78,10 +78,9 @@ interface SurrogateInterface
|
|||
/**
|
||||
* Handles a Surrogate from the cache.
|
||||
*
|
||||
* @param HttpCache $cache An HttpCache instance
|
||||
* @param string $uri The main URI
|
||||
* @param string $alt An alternative URI
|
||||
* @param bool $ignoreErrors Whether to ignore errors or not
|
||||
* @param string $uri The main URI
|
||||
* @param string $alt An alternative URI
|
||||
* @param bool $ignoreErrors Whether to ignore errors or not
|
||||
*
|
||||
* @return string
|
||||
*
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue