migration symfony 5 4 (#300)

* symfony 5.4 (diff dev)

* symfony 5.4 (working)

* symfony 5.4 (update autoload)

* symfony 5.4 (remove swiftmailer mailer implementation)

* symfony 5.4 (php doc and split Global accessor class)


### Impacted packages:

composer require php:">=7.2.5 <8.0.0" symfony/console:5.4.* symfony/dotenv:5.4.* symfony/framework-bundle:5.4.* symfony/twig-bundle:5.4.* symfony/yaml:5.4.* --update-with-dependencies

composer require symfony/stopwatch:5.4.* symfony/web-profiler-bundle:5.4.* --dev --update-with-dependencies
This commit is contained in:
bdalsass
2022-06-16 09:13:24 +02:00
committed by GitHub
parent abb13b70b9
commit 79da71ecf8
2178 changed files with 87439 additions and 59451 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());

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,
@@ -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;

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;
@@ -40,7 +42,14 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
*
* 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
* 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)
*
* * default_ttl The number of seconds that a cache entry should be considered
* fresh when no explicit freshness information is provided in
@@ -87,13 +96,19 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
'allow_revalidate' => false,
'stale_while_revalidate' => 2,
'stale_if_error' => 60,
'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 A StoreInterface instance
* @return StoreInterface
*/
public function getStore()
{
@@ -103,17 +118,34 @@ 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()
{
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.
*
* @return string A log message
* @return string
*/
public function getLog()
{
@@ -126,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()
{
@@ -138,7 +170,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Gets the Kernel instance.
*
* @return HttpKernelInterface An HttpKernelInterface instance
* @return HttpKernelInterface
*/
public function getKernel()
{
@@ -148,7 +180,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Gets the Surrogate instance.
*
* @return SurrogateInterface A Surrogate instance
* @return SurrogateInterface
*
* @throws \LogicException
*/
@@ -160,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
@@ -177,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);
@@ -194,12 +226,12 @@ 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::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);
@@ -226,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');
@@ -241,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);
@@ -290,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);
@@ -340,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;
@@ -357,7 +384,7 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
// add our cached last-modified validator
if ($entry->headers->has('Last-Modified')) {
$subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified'));
$subRequest->headers->set('If-Modified-Since', $entry->headers->get('Last-Modified'));
}
// Add our cached etag validator to the environment.
@@ -366,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);
@@ -405,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;
@@ -420,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);
@@ -441,16 +467,16 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
* @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);
/*
* Support stale-if-error given on Responses or as a config option.
@@ -514,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)
{
@@ -641,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));
@@ -663,21 +687,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.
*
* @return string
*/
private function getTraceKey(Request $request)
private function getTraceKey(Request $request): string
{
$path = $request->getPathInfo();
if ($qs = $request->getQueryString()) {
@@ -690,10 +709,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Checks whether the given (cached) response may be served as "stale" when a revalidation
* is currently in progress.
*
* @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');
@@ -706,12 +723,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) {

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 ? (int) $expires->format('U') - (int) $response->getDate()->format('U') : null;
$this->storeRelativeAgeDirective('expires', $expires >= 0 ? $expires : null, 0);
$this->storeRelativeAgeDirective('expires', $expires >= 0 ? $expires : null, 0, $isHeuristicallyCacheable);
}
/**
@@ -153,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.
@@ -199,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);
}

View File

@@ -25,22 +25,21 @@ 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 = [];
/**
* @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)) {
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 = [];
}
/**
@@ -68,10 +67,10 @@ 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');
$h = fopen($path, 'c');
if (!flock($h, \LOCK_EX | \LOCK_NB)) {
fclose($h);
@@ -112,11 +111,11 @@ 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');
$h = fopen($path, 'r');
flock($h, \LOCK_EX | \LOCK_NB, $wouldBlock);
flock($h, \LOCK_UN); // release the lock we just acquired
fclose($h);
@@ -127,7 +126,7 @@ 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)
{
@@ -168,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
*/
@@ -209,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;
}
}
@@ -267,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;
@@ -281,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;
}
@@ -295,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) ?: [];
}
/**
@@ -314,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);
@@ -331,12 +322,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])) {
@@ -345,7 +332,7 @@ class Store implements StoreInterface
unset($this->locks[$key]);
}
if (file_exists($path = $this->getPath($key))) {
if (is_file($path = $this->getPath($key))) {
unlink($path);
return true;
@@ -356,28 +343,18 @@ class Store implements StoreInterface
/**
* Loads data for the given key.
*
* @param string $key The store key
*
* @return string|null The data associated with the key
*/
private function load($key)
private function load(string $key): ?string
{
$path = $this->getPath($key);
return file_exists($path) && false !== ($contents = file_get_contents($path)) ? $contents : null;
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
* @param bool $overwrite Whether existing data should be overwritten
*
* @return bool
*/
private function save($key, $data, $overwrite = true)
private function save(string $key, string $data, bool $overwrite = true): bool
{
$path = $this->getPath($key);
@@ -396,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;
@@ -427,7 +404,7 @@ class Store implements StoreInterface
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);
}
@@ -442,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)
{
@@ -451,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];
@@ -465,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()];
@@ -488,13 +459,8 @@ 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 $path Path to the Response body
*
* @return Response
*/
private function restoreResponse($headers, $path = null)
private function restoreResponse(array $headers, string $path = null): Response
{
$status = $headers['X-Status'][0];
unset($headers['X-Status']);

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,42 +23,26 @@ use Symfony\Component\HttpKernel\HttpKernelInterface;
*/
class SubRequestHandler
{
/**
* @return Response
*/
public static function handle(HttpKernelInterface $kernel, Request $request, $type, $catch)
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();
$trustedHeaderSet = Request::getTrustedHeaderSet();
if (method_exists(Request::class, 'getTrustedHeaderName')) {
Request::setTrustedProxies($trustedProxies, -1);
$trustedHeaders = [
Request::HEADER_FORWARDED => Request::getTrustedHeaderName(Request::HEADER_FORWARDED, false),
Request::HEADER_X_FORWARDED_FOR => Request::getTrustedHeaderName(Request::HEADER_X_FORWARDED_FOR, false),
Request::HEADER_X_FORWARDED_HOST => Request::getTrustedHeaderName(Request::HEADER_X_FORWARDED_HOST, false),
Request::HEADER_X_FORWARDED_PROTO => Request::getTrustedHeaderName(Request::HEADER_X_FORWARDED_PROTO, false),
Request::HEADER_X_FORWARDED_PORT => Request::getTrustedHeaderName(Request::HEADER_X_FORWARDED_PORT, false),
];
Request::setTrustedProxies($trustedProxies, $trustedHeaderSet);
} else {
$trustedHeaders = [
Request::HEADER_FORWARDED => 'FORWARDED',
Request::HEADER_X_FORWARDED_FOR => 'X_FORWARDED_FOR',
Request::HEADER_X_FORWARDED_HOST => 'X_FORWARDED_HOST',
Request::HEADER_X_FORWARDED_PROTO => 'X_FORWARDED_PROTO',
Request::HEADER_X_FORWARDED_PORT => 'X_FORWARDED_PORT',
];
}
// remove untrusted values
$remoteAddr = $request->server->get('REMOTE_ADDR');
if (!IpUtils::checkIp($remoteAddr, $trustedProxies)) {
foreach ($trustedHeaders as $key => $name) {
if ($trustedHeaderSet & $key) {
$request->headers->remove($name);
$request->server->remove('HTTP_'.strtoupper(str_replace('-', '_', $name)));
}
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);
$request->server->remove('HTTP_'.$name);
}
}
@@ -77,16 +61,16 @@ class SubRequestHandler
// set trusted values, reusing as much as possible the global trusted settings
if (Request::HEADER_FORWARDED & $trustedHeaderSet) {
$trustedValues[0] .= sprintf(';host="%s";proto=%s', $request->getHttpHost(), $request->getScheme());
$request->headers->set($name = $trustedHeaders[Request::HEADER_FORWARDED], $v = implode(', ', $trustedValues));
$request->server->set('HTTP_'.strtoupper(str_replace('-', '_', $name)), $v);
$request->headers->set('Forwarded', $v = implode(', ', $trustedValues));
$request->server->set('HTTP_FORWARDED', $v);
}
if (Request::HEADER_X_FORWARDED_FOR & $trustedHeaderSet) {
$request->headers->set($name = $trustedHeaders[Request::HEADER_X_FORWARDED_FOR], $v = implode(', ', $trustedIps));
$request->server->set('HTTP_'.strtoupper(str_replace('-', '_', $name)), $v);
$request->headers->set('X-Forwarded-For', $v = implode(', ', $trustedIps));
$request->server->set('HTTP_X_FORWARDED_FOR', $v);
} elseif (!(Request::HEADER_FORWARDED & $trustedHeaderSet)) {
Request::setTrustedProxies($trustedProxies, $trustedHeaderSet | Request::HEADER_X_FORWARDED_FOR);
$request->headers->set($name = $trustedHeaders[Request::HEADER_X_FORWARDED_FOR], $v = implode(', ', $trustedIps));
$request->server->set('HTTP_'.strtoupper(str_replace('-', '_', $name)), $v);
$request->headers->set('X-Forwarded-For', $v = implode(', ', $trustedIps));
$request->server->set('HTTP_X_FORWARDED_FOR', $v);
}
// fix the client IP address by setting it to 127.0.0.1,

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);
}