Update to laravel 7

This commit is contained in:
KodeStar
2022-03-10 11:54:29 +00:00
parent 61a5a1a8b0
commit f9a19fce91
7170 changed files with 274189 additions and 283773 deletions

View File

@@ -41,7 +41,7 @@ abstract class AbstractSurrogate implements SurrogateInterface
/**
* Returns a new cache strategy instance.
*
* @return ResponseCacheStrategyInterface A ResponseCacheStrategyInterface instance
* @return ResponseCacheStrategyInterface
*/
public function createCacheStrategy()
{
@@ -57,7 +57,7 @@ abstract class AbstractSurrogate implements SurrogateInterface
return false;
}
return false !== strpos($value, sprintf('%s/1.0', strtoupper($this->getName())));
return str_contains($value, sprintf('%s/1.0', strtoupper($this->getName())));
}
/**
@@ -88,7 +88,7 @@ abstract class AbstractSurrogate implements SurrogateInterface
/**
* {@inheritdoc}
*/
public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors)
public function handle(HttpCache $cache, string $uri, string $alt, bool $ignoreErrors)
{
$subRequest = Request::create($uri, Request::METHOD_GET, [], $cache->getRequest()->cookies->all(), [], $cache->getRequest()->server->all());
@@ -96,7 +96,7 @@ abstract class AbstractSurrogate implements SurrogateInterface
$response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true);
if (!$response->isSuccessful()) {
throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode()));
throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %d).', $subRequest->getUri(), $response->getStatusCode()));
}
return $response->getContent();
@@ -109,6 +109,8 @@ abstract class AbstractSurrogate implements SurrogateInterface
throw $e;
}
}
return '';
}
/**

View File

@@ -37,7 +37,7 @@ class Esi extends AbstractSurrogate
*/
public function addSurrogateControl(Response $response)
{
if (false !== strpos($response->getContent(), '<esi:include')) {
if (str_contains($response->getContent(), '<esi:include')) {
$response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
}
}
@@ -45,7 +45,7 @@ class Esi extends AbstractSurrogate
/**
* {@inheritdoc}
*/
public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '')
public function renderIncludeTag(string $uri, string $alt = null, bool $ignoreErrors = true, string $comment = '')
{
$html = sprintf('<esi:include src="%s"%s%s />',
$uri,
@@ -80,13 +80,13 @@ class Esi extends AbstractSurrogate
$content = preg_replace('#<esi\:remove>.*?</esi\:remove>#s', '', $content);
$content = preg_replace('#<esi\:comment[^>]+>#s', '', $content);
$chunks = preg_split('#<esi\:include\s+(.*?)\s*(?:/|</esi\:include)>#', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
$chunks = preg_split('#<esi\:include\s+(.*?)\s*(?:/|</esi\:include)>#', $content, -1, \PREG_SPLIT_DELIM_CAPTURE);
$chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]);
$i = 1;
while (isset($chunks[$i])) {
$options = [];
preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, \PREG_SET_ORDER);
foreach ($matches as $set) {
$options[$set[1]] = $set[2];
}
@@ -97,7 +97,7 @@ class Esi extends AbstractSurrogate
$chunks[$i] = sprintf('<?php echo $this->surrogate->handle($this, %s, %s, %s) ?>'."\n",
var_export($options['src'], true),
var_export(isset($options['alt']) ? $options['alt'] : '', true),
var_export($options['alt'] ?? '', true),
isset($options['onerror']) && 'continue' === $options['onerror'] ? 'true' : 'false'
);
++$i;
@@ -111,5 +111,7 @@ class Esi extends AbstractSurrogate
// remove ESI/1.0 from the Surrogate-Control header
$this->removeFromControl($response);
return $response;
}
}

View File

@@ -5,12 +5,14 @@
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/*
* 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.
*/
namespace Symfony\Component\HttpKernel\HttpCache;
@@ -44,7 +46,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* 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
* main 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)
@@ -98,15 +100,15 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
'trace_header' => 'X-Symfony-Cache',
], $options);
if (!isset($options['trace_level']) && $this->options['debug']) {
$this->options['trace_level'] = 'full';
if (!isset($options['trace_level'])) {
$this->options['trace_level'] = $this->options['debug'] ? 'full' : 'none';
}
}
/**
* Gets the current store.
*
* @return StoreInterface A StoreInterface instance
* @return StoreInterface
*/
public function getStore()
{
@@ -116,7 +118,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Returns an array of events that took place during processing of the last request.
*
* @return array An array of events
* @return array
*/
public function getTraces()
{
@@ -143,7 +145,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Returns a log message for the events of the last request processing.
*
* @return string A log message
* @return string
*/
public function getLog()
{
@@ -156,9 +158,9 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
}
/**
* Gets the Request instance associated with the master request.
* Gets the Request instance associated with the main request.
*
* @return Request A Request instance
* @return Request
*/
public function getRequest()
{
@@ -168,7 +170,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Gets the Kernel instance.
*
* @return HttpKernelInterface An HttpKernelInterface instance
* @return HttpKernelInterface
*/
public function getKernel()
{
@@ -178,7 +180,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Gets the Surrogate instance.
*
* @return SurrogateInterface A Surrogate instance
* @return SurrogateInterface
*
* @throws \LogicException
*/
@@ -190,10 +192,10 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* {@inheritdoc}
*/
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true)
{
// 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) {
if (HttpKernelInterface::MAIN_REQUEST === $type) {
$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
@@ -207,7 +209,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$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);
@@ -224,12 +226,12 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$this->restoreResponseBody($request, $response);
if (HttpKernelInterface::MASTER_REQUEST === $type) {
if (HttpKernelInterface::MAIN_REQUEST === $type) {
$this->addTraces($response);
}
if (null !== $this->surrogate) {
if (HttpKernelInterface::MASTER_REQUEST === $type) {
if (HttpKernelInterface::MAIN_REQUEST === $type) {
$this->surrogateCacheStrategy->update($response);
} else {
$this->surrogateCacheStrategy->add($response);
@@ -256,12 +258,11 @@ 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
* @return Response
*/
protected function pass(Request $request, $catch = false)
protected function pass(Request $request, bool $catch = false)
{
$this->record($request, 'pass');
@@ -271,16 +272,15 @@ 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
* @return Response
*
* @throws \Exception
*
* @see RFC2616 13.10
*/
protected function invalidate(Request $request, $catch = false)
protected function invalidate(Request $request, bool $catch = false)
{
$response = $this->pass($request, $catch);
@@ -320,14 +320,13 @@ 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
* @return Response
*
* @throws \Exception
*/
protected function lookup(Request $request, $catch = false)
protected function lookup(Request $request, bool $catch = false)
{
try {
$entry = $this->store->lookup($request);
@@ -353,6 +352,10 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
return $this->validate($request, $entry, $catch);
}
if ($entry->headers->hasCacheControlDirective('no-cache')) {
return $this->validate($request, $entry, $catch);
}
$this->record($request, 'fresh');
$entry->headers->set('Age', $entry->getAge());
@@ -366,13 +369,11 @@ 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
* @return Response
*/
protected function validate(Request $request, Response $entry, $catch = false)
protected function validate(Request $request, Response $entry, bool $catch = false)
{
$subRequest = clone $request;
@@ -382,7 +383,9 @@ 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
@@ -390,7 +393,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
$cachedEtags = $entry->getEtag() ? [$entry->getEtag()] : [];
$requestEtags = $request->getETags();
if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) {
$subRequest->headers->set('if_none_match', implode(', ', $etags));
$subRequest->headers->set('If-None-Match', implode(', ', $etags));
}
$response = $this->forward($subRequest, $catch, $entry);
@@ -429,12 +432,11 @@ 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
* @return Response
*/
protected function fetch(Request $request, $catch = false)
protected function fetch(Request $request, bool $catch = false)
{
$subRequest = clone $request;
@@ -444,8 +446,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
}
// avoid that the backend sends no content
$subRequest->headers->remove('if_modified_since');
$subRequest->headers->remove('if_none_match');
$subRequest->headers->remove('If-Modified-Since');
$subRequest->headers->remove('If-None-Match');
$response = $this->forward($subRequest, $catch);
@@ -462,28 +464,51 @@ 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
* @return Response
*/
protected function forward(Request $request, $catch = false, Response $entry = null)
protected function forward(Request $request, bool $catch = false, Response $entry = null)
{
if ($this->surrogate) {
$this->surrogate->addSurrogateCapability($request);
}
// always a "master" request (as the real master request can be in cache)
$response = SubRequestHandler::handle($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST, $catch);
$response = SubRequestHandler::handle($this->kernel, $request, HttpKernelInterface::MAIN_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(), [500, 502, 503, 504])) {
/*
* Support stale-if-error given on Responses or as a config option.
* RFC 7234 summarizes in Section 4.2.4 (but also mentions with the individual
* Cache-Control directives) that
*
* A cache MUST NOT generate a stale response if it is prohibited by an
* explicit in-protocol directive (e.g., by a "no-store" or "no-cache"
* cache directive, a "must-revalidate" cache-response-directive, or an
* applicable "s-maxage" or "proxy-revalidate" cache-response-directive;
* see Section 5.2.2).
*
* https://tools.ietf.org/html/rfc7234#section-4.2.4
*
* We deviate from this in one detail, namely that we *do* serve entries in the
* stale-if-error case even if they have a `s-maxage` Cache-Control directive.
*/
if (null !== $entry
&& \in_array($response->getStatusCode(), [500, 502, 503, 504])
&& !$entry->headers->hasCacheControlDirective('no-cache')
&& !$entry->mustRevalidate()
) {
if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
$age = $this->options['stale_if_error'];
}
if (abs($entry->getTtl()) < $age) {
/*
* stale-if-error gives the (extra) time that the Response may be used *after* it has become stale.
* So we compare the time the $entry has been sitting in the cache already with the
* time it was fresh plus the allowed grace period.
*/
if ($entry->getAge() <= $entry->getMaxAge() + $age) {
$this->record($request, 'stale-if-error');
return $entry;
@@ -515,7 +540,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Checks whether the cache entry is "fresh enough" to satisfy the Request.
*
* @return bool true if the cache entry if fresh enough, false otherwise
* @return bool
*/
protected function isFreshEnough(Request $request, Response $entry)
{
@@ -642,10 +667,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));

View File

@@ -17,7 +17,7 @@ use Symfony\Component\HttpFoundation\Response;
* ResponseCacheStrategy knows how to compute the Response cache HTTP header
* based on the different response cache headers.
*
* This implementation changes the master response TTL to the smallest TTL received
* This implementation changes the main response TTL to the smallest TTL received
* or force validation if one of the surrogates has validation cache strategy.
*
* @author Fabien Potencier <fabien@symfony.com>
@@ -27,12 +27,12 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
/**
* 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'];
private const OVERRIDE_DIRECTIVES = ['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 const INHERIT_DIRECTIVES = ['public', 'immutable'];
private $embeddedResponses = 0;
private $isNotCacheableResponseEmbedded = false;
@@ -60,13 +60,13 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
{
++$this->embeddedResponses;
foreach (self::$overrideDirectives as $directive) {
foreach (self::OVERRIDE_DIRECTIVES as $directive) {
if ($response->headers->hasCacheControlDirective($directive)) {
$this->flagDirectives[$directive] = true;
}
}
foreach (self::$inheritDirectives as $directive) {
foreach (self::INHERIT_DIRECTIVES as $directive) {
if (false !== $this->flagDirectives[$directive]) {
$this->flagDirectives[$directive] = $response->headers->hasCacheControlDirective($directive);
}
@@ -81,12 +81,15 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
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);
$isHeuristicallyCacheable = $response->headers->hasCacheControlDirective('public');
$maxAge = $response->headers->hasCacheControlDirective('max-age') ? (int) $response->headers->getCacheControlDirective('max-age') : null;
$this->storeRelativeAgeDirective('max-age', $maxAge, $age, $isHeuristicallyCacheable);
$sharedMaxAge = $response->headers->hasCacheControlDirective('s-maxage') ? (int) $response->headers->getCacheControlDirective('s-maxage') : $maxAge;
$this->storeRelativeAgeDirective('s-maxage', $sharedMaxAge, $age, $isHeuristicallyCacheable);
$expires = $response->getExpires();
$expires = null !== $expires ? $expires->format('U') - $response->getDate()->format('U') : null;
$this->storeRelativeAgeDirective('expires', $expires >= 0 ? $expires : null, 0);
$expires = null !== $expires ? (int) $expires->format('U') - (int) $response->getDate()->format('U') : null;
$this->storeRelativeAgeDirective('expires', $expires >= 0 ? $expires : null, 0, $isHeuristicallyCacheable);
}
/**
@@ -110,8 +113,6 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
$response->headers->set('Age', $this->age);
if ($this->isNotCacheableResponseEmbedded) {
$response->setExpires($response->getDate());
if ($this->flagDirectives['no-store']) {
$response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');
} else {
@@ -130,14 +131,13 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
$response->headers->set('Cache-Control', implode(', ', array_keys($flags)));
$maxAge = null;
$sMaxage = null;
if (\is_numeric($this->ageDirectives['max-age'])) {
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'])) {
if (is_numeric($this->ageDirectives['s-maxage'])) {
$sMaxage = $this->ageDirectives['s-maxage'] + $this->age;
if ($maxAge !== $sMaxage) {
@@ -145,7 +145,7 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
}
}
if (\is_numeric($this->ageDirectives['expires'])) {
if (is_numeric($this->ageDirectives['expires'])) {
$date = clone $response->getDate();
$date->modify('+'.($this->ageDirectives['expires'] + $this->age).' seconds');
$response->setExpires($date);
@@ -156,10 +156,8 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
* RFC2616, Section 13.4.
*
* @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
*
* @return bool
*/
private function willMakeFinalResponseUncacheable(Response $response)
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.
@@ -202,15 +200,29 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
* 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.
* minimal value of each instruction.
*
* @param string $directive
* @param int|null $value
* @param int $age
* If the value is NULL and the isHeuristicallyCacheable parameter is false, the directive will
* not be set on the final response. In this case, not all responses had the directive set and no
* value can be found that satisfies the requirements of all responses. The directive will be dropped
* from the final response.
*
* If the isHeuristicallyCacheable parameter is true, however, the current response has been marked
* as cacheable in a public (shared) cache, but did not provide an explicit lifetime that would serve
* as an upper bound. In this case, we can proceed and possibly keep the directive on the final response.
*/
private function storeRelativeAgeDirective($directive, $value, $age)
private function storeRelativeAgeDirective(string $directive, ?int $value, int $age, bool $isHeuristicallyCacheable)
{
if (null === $value) {
if ($isHeuristicallyCacheable) {
/*
* See https://datatracker.ietf.org/doc/html/rfc7234#section-4.2.2
* This particular response does not require maximum lifetime; heuristics might be applied.
* Other responses, however, might have more stringent requirements on maximum lifetime.
* So, return early here so that the final response can have the more limiting value set.
*/
return;
}
$this->ageDirectives[$directive] = false;
}

View File

@@ -34,7 +34,7 @@ class Ssi extends AbstractSurrogate
*/
public function addSurrogateControl(Response $response)
{
if (false !== strpos($response->getContent(), '<!--#include')) {
if (str_contains($response->getContent(), '<!--#include')) {
$response->headers->set('Surrogate-Control', 'content="SSI/1.0"');
}
}
@@ -42,7 +42,7 @@ class Ssi extends AbstractSurrogate
/**
* {@inheritdoc}
*/
public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '')
public function renderIncludeTag(string $uri, string $alt = null, bool $ignoreErrors = true, string $comment = '')
{
return sprintf('<!--#include virtual="%s" -->', $uri);
}
@@ -65,13 +65,13 @@ class Ssi extends AbstractSurrogate
// we don't use a proper XML parser here as we can have SSI tags in a plain text response
$content = $response->getContent();
$chunks = preg_split('#<!--\#include\s+(.*?)\s*-->#', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
$chunks = preg_split('#<!--\#include\s+(.*?)\s*-->#', $content, -1, \PREG_SPLIT_DELIM_CAPTURE);
$chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]);
$i = 1;
while (isset($chunks[$i])) {
$options = [];
preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
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;
}
}

View File

@@ -25,8 +25,10 @@ use Symfony\Component\HttpFoundation\Response;
class Store implements StoreInterface
{
protected $root;
/** @var \SplObjectStorage<Request, string> */
private $keyCache;
private $locks;
/** @var array<string, resource> */
private $locks = [];
/**
* @throws \RuntimeException
@@ -34,11 +36,10 @@ class Store implements StoreInterface
public function __construct(string $root)
{
$this->root = $root;
if (!file_exists($this->root) && !@mkdir($this->root, 0777, true) && !is_dir($this->root)) {
if (!is_dir($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 = [];
}
/**
@@ -48,7 +49,7 @@ class Store implements StoreInterface
{
// unlock everything
foreach ($this->locks as $lock) {
flock($lock, LOCK_UN);
flock($lock, \LOCK_UN);
fclose($lock);
}
@@ -66,11 +67,11 @@ class Store implements StoreInterface
if (!isset($this->locks[$key])) {
$path = $this->getPath($key);
if (!file_exists(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) {
if (!is_dir(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) {
return $path;
}
$h = fopen($path, 'cb');
if (!flock($h, LOCK_EX | LOCK_NB)) {
$h = fopen($path, 'c');
if (!flock($h, \LOCK_EX | \LOCK_NB)) {
fclose($h);
return $path;
@@ -92,7 +93,7 @@ class Store implements StoreInterface
$key = $this->getCacheKey($request);
if (isset($this->locks[$key])) {
flock($this->locks[$key], LOCK_UN);
flock($this->locks[$key], \LOCK_UN);
fclose($this->locks[$key]);
unset($this->locks[$key]);
@@ -110,13 +111,13 @@ class Store implements StoreInterface
return true; // shortcut if lock held by this process
}
if (!file_exists($path = $this->getPath($key))) {
if (!is_file($path = $this->getPath($key))) {
return false;
}
$h = fopen($path, 'rb');
flock($h, LOCK_EX | LOCK_NB, $wouldBlock);
flock($h, LOCK_UN); // release the lock we just acquired
$h = fopen($path, 'r');
flock($h, \LOCK_EX | \LOCK_NB, $wouldBlock);
flock($h, \LOCK_UN); // release the lock we just acquired
fclose($h);
return (bool) $wouldBlock;
@@ -125,14 +126,14 @@ class Store implements StoreInterface
/**
* Locates a cached Response for the Request provided.
*
* @return Response|null A Response instance, or null if no cache entry was found
* @return Response|null
*/
public function lookup(Request $request)
{
$key = $this->getCacheKey($request);
if (!$entries = $this->getMetadata($key)) {
return;
return null;
}
// find a cached entry that matches the request.
@@ -146,17 +147,18 @@ class Store implements StoreInterface
}
if (null === $match) {
return;
return null;
}
$headers = $match[1];
if (file_exists($body = $this->getPath($headers['x-content-digest'][0]))) {
return $this->restoreResponse($headers, $body);
if (file_exists($path = $this->getPath($headers['x-content-digest'][0]))) {
return $this->restoreResponse($headers, $path);
}
// 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;
}
/**
@@ -165,7 +167,7 @@ class Store implements StoreInterface
* Existing entries are read and any that match the response are removed. This
* method calls write with the new list of cache entries.
*
* @return string The key under which the response is stored
* @return string
*
* @throws \RuntimeException
*/
@@ -174,16 +176,25 @@ class Store implements StoreInterface
$key = $this->getCacheKey($request);
$storedEnv = $this->persistRequest($request);
// write the response body to the entity store if this is the original response
if (!$response->headers->has('X-Content-Digest')) {
$digest = $this->generateContentDigest($response);
if (false === $this->save($digest, $response->getContent())) {
throw new \RuntimeException('Unable to store the entity.');
if ($response->headers->has('X-Body-File')) {
// Assume the response came from disk, but at least perform some safeguard checks
if (!$response->headers->has('X-Content-Digest')) {
throw new \RuntimeException('A restored response must have the X-Content-Digest header.');
}
$digest = $response->headers->get('X-Content-Digest');
if ($this->getPath($digest) !== $response->headers->get('X-Body-File')) {
throw new \RuntimeException('X-Body-File and X-Content-Digest do not match.');
}
// Everything seems ok, omit writing content to disk
} else {
$digest = $this->generateContentDigest($response);
$response->headers->set('X-Content-Digest', $digest);
if (!$this->save($digest, $response->getContent(), false)) {
throw new \RuntimeException('Unable to store the entity.');
}
if (!$response->headers->has('Transfer-Encoding')) {
$response->headers->set('Content-Length', \strlen($response->getContent()));
}
@@ -197,7 +208,7 @@ class Store implements StoreInterface
$entry[1]['vary'] = [''];
}
if ($entry[1]['vary'][0] != $vary || !$this->requestsMatch($vary, $entry[0], $storedEnv)) {
if ($entry[1]['vary'][0] != $vary || !$this->requestsMatch($vary ?? '', $entry[0], $storedEnv)) {
$entries[] = $entry;
}
}
@@ -207,7 +218,7 @@ class Store implements StoreInterface
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.');
}
@@ -246,7 +257,7 @@ class Store implements StoreInterface
}
}
if ($modified && false === $this->save($key, serialize($entries))) {
if ($modified && !$this->save($key, serialize($entries))) {
throw new \RuntimeException('Unable to store the metadata.');
}
}
@@ -255,13 +266,11 @@ class Store implements StoreInterface
* Determines whether two Request HTTP header sets are non-varying based on
* the vary response header value provided.
*
* @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
* @param string|null $vary A Response vary header
* @param array $env1 A Request HTTP header array
* @param array $env2 A Request HTTP header array
*/
private function requestsMatch($vary, $env1, $env2)
private function requestsMatch(?string $vary, array $env1, array $env2): bool
{
if (empty($vary)) {
return true;
@@ -269,8 +278,8 @@ class Store implements StoreInterface
foreach (preg_split('/[\s,]+/', $vary) as $header) {
$key = str_replace('_', '-', strtolower($header));
$v1 = isset($env1[$key]) ? $env1[$key] : null;
$v2 = isset($env2[$key]) ? $env2[$key] : null;
$v1 = $env1[$key] ?? null;
$v2 = $env2[$key] ?? null;
if ($v1 !== $v2) {
return false;
}
@@ -283,18 +292,14 @@ 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 [];
}
return unserialize($entries);
return unserialize($entries) ?: [];
}
/**
@@ -302,11 +307,9 @@ class Store implements StoreInterface
*
* This method purges both the HTTP and the HTTPS version of the cache entry.
*
* @param string $url A URL
*
* @return bool true if the URL exists with either HTTP or HTTPS scheme and has been purged, false otherwise
*/
public function purge($url)
public function purge(string $url)
{
$http = preg_replace('#^https:#', 'http:', $url);
$https = preg_replace('#^http:#', 'https:', $url);
@@ -319,21 +322,17 @@ 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])) {
flock($this->locks[$key], LOCK_UN);
flock($this->locks[$key], \LOCK_UN);
fclose($this->locks[$key]);
unset($this->locks[$key]);
}
if (file_exists($path = $this->getPath($key))) {
if (is_file($path = $this->getPath($key))) {
unlink($path);
return true;
@@ -344,30 +343,25 @@ 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 is_file($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 $overwrite = true): bool
{
$path = $this->getPath($key);
if (!$overwrite && file_exists($path)) {
return true;
}
if (isset($this->locks[$key])) {
$fp = $this->locks[$key];
@ftruncate($fp, 0);
@@ -379,12 +373,12 @@ class Store implements StoreInterface
return false;
}
} else {
if (!file_exists(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) {
if (!is_dir(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) {
return false;
}
$tmpFile = tempnam(\dirname($path), basename($path));
if (false === $fp = @fopen($tmpFile, 'wb')) {
if (false === $fp = @fopen($tmpFile, 'w')) {
@unlink($tmpFile);
return false;
@@ -406,9 +400,11 @@ class Store implements StoreInterface
}
@chmod($path, 0666 & ~umask());
return true;
}
public function getPath($key)
public function getPath(string $key)
{
return $this->root.\DIRECTORY_SEPARATOR.substr($key, 0, 2).\DIRECTORY_SEPARATOR.substr($key, 2, 2).\DIRECTORY_SEPARATOR.substr($key, 4, 2).\DIRECTORY_SEPARATOR.substr($key, 6);
}
@@ -423,7 +419,7 @@ class Store implements StoreInterface
* headers, use a Vary header to indicate them, and each representation will
* be stored independently under the same cache key.
*
* @return string A key for the given Request
* @return string
*/
protected function generateCacheKey(Request $request)
{
@@ -432,10 +428,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];
@@ -446,20 +440,16 @@ 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'] = [$response->getStatusCode()];
@@ -469,21 +459,16 @@ class Store implements StoreInterface
/**
* 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 $path = null): Response
{
$status = $headers['X-Status'][0];
unset($headers['X-Status']);
if (null !== $body) {
$headers['X-Body-File'] = [$body];
if (null !== $path) {
$headers['X-Body-File'] = [$path];
}
return new Response($body, $status, $headers);
return new Response($path, $status, $headers);
}
}

View File

@@ -27,7 +27,7 @@ interface StoreInterface
/**
* Locates a cached Response for the Request provided.
*
* @return Response|null A Response instance, or null if no cache entry was found
* @return Response|null
*/
public function lookup(Request $request);
@@ -70,11 +70,9 @@ interface 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
*/
public function purge($url);
public function purge(string $url);
/**
* Cleanups storage.

View File

@@ -23,7 +23,7 @@ use Symfony\Component\HttpKernel\HttpKernelInterface;
*/
class SubRequestHandler
{
public static function handle(HttpKernelInterface $kernel, Request $request, $type, $catch): Response
public static function handle(HttpKernelInterface $kernel, Request $request, int $type, bool $catch): Response
{
// save global state related to trusted headers and proxies
$trustedProxies = Request::getTrustedProxies();
@@ -31,13 +31,14 @@ class SubRequestHandler
// remove untrusted values
$remoteAddr = $request->server->get('REMOTE_ADDR');
if (!IpUtils::checkIp($remoteAddr, $trustedProxies)) {
if (!$remoteAddr || !IpUtils::checkIp($remoteAddr, $trustedProxies)) {
$trustedHeaders = [
'FORWARDED' => $trustedHeaderSet & Request::HEADER_FORWARDED,
'X_FORWARDED_FOR' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_FOR,
'X_FORWARDED_HOST' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_HOST,
'X_FORWARDED_PROTO' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_PROTO,
'X_FORWARDED_PORT' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_PORT,
'X_FORWARDED_PREFIX' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_PREFIX,
];
foreach (array_filter($trustedHeaders) as $name => $key) {
$request->headers->remove($name);

View File

@@ -26,14 +26,14 @@ interface SurrogateInterface
/**
* Returns a new cache strategy instance.
*
* @return ResponseCacheStrategyInterface A ResponseCacheStrategyInterface instance
* @return ResponseCacheStrategyInterface
*/
public function createCacheStrategy();
/**
* Checks that at least one surrogate has Surrogate capability.
*
* @return bool true if one surrogate has Surrogate capability, false otherwise
* @return bool
*/
public function hasSurrogateCapability(Request $request);
@@ -52,21 +52,19 @@ interface SurrogateInterface
/**
* Checks that the Response needs to be parsed for Surrogate tags.
*
* @return bool true if the Response needs to be parsed, false otherwise
* @return bool
*/
public function needsParsing(Response $response);
/**
* Renders a Surrogate tag.
*
* @param string $uri A URI
* @param string $alt An alternate URI
* @param bool $ignoreErrors Whether to ignore errors or not
* @param string $comment A comment to add as an esi:include tag
* @param string $alt An alternate URI
* @param string $comment A comment to add as an esi:include tag
*
* @return string
*/
public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '');
public function renderIncludeTag(string $uri, string $alt = null, bool $ignoreErrors = true, string $comment = '');
/**
* Replaces a Response Surrogate tags with the included resource content.
@@ -78,15 +76,12 @@ 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 $alt An alternative URI
*
* @return string
*
* @throws \RuntimeException
* @throws \Exception
*/
public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors);
public function handle(HttpCache $cache, string $uri, string $alt, bool $ignoreErrors);
}