ResponseCacheStrategy.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\HttpCache;
  11. use Symfony\Component\HttpFoundation\Response;
  12. /**
  13. * ResponseCacheStrategy knows how to compute the Response cache HTTP header
  14. * based on the different response cache headers.
  15. *
  16. * This implementation changes the main response TTL to the smallest TTL received
  17. * or force validation if one of the surrogates has validation cache strategy.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class ResponseCacheStrategy implements ResponseCacheStrategyInterface
  22. {
  23. /**
  24. * Cache-Control headers that are sent to the final response if they appear in ANY of the responses.
  25. */
  26. private const OVERRIDE_DIRECTIVES = ['private', 'no-cache', 'no-store', 'no-transform', 'must-revalidate', 'proxy-revalidate'];
  27. /**
  28. * Cache-Control headers that are sent to the final response if they appear in ALL of the responses.
  29. */
  30. private const INHERIT_DIRECTIVES = ['public', 'immutable'];
  31. private $embeddedResponses = 0;
  32. private $isNotCacheableResponseEmbedded = false;
  33. private $age = 0;
  34. private $flagDirectives = [
  35. 'no-cache' => null,
  36. 'no-store' => null,
  37. 'no-transform' => null,
  38. 'must-revalidate' => null,
  39. 'proxy-revalidate' => null,
  40. 'public' => null,
  41. 'private' => null,
  42. 'immutable' => null,
  43. ];
  44. private $ageDirectives = [
  45. 'max-age' => null,
  46. 's-maxage' => null,
  47. 'expires' => false,
  48. ];
  49. /**
  50. * {@inheritdoc}
  51. */
  52. public function add(Response $response)
  53. {
  54. ++$this->embeddedResponses;
  55. foreach (self::OVERRIDE_DIRECTIVES as $directive) {
  56. if ($response->headers->hasCacheControlDirective($directive)) {
  57. $this->flagDirectives[$directive] = true;
  58. }
  59. }
  60. foreach (self::INHERIT_DIRECTIVES as $directive) {
  61. if (false !== $this->flagDirectives[$directive]) {
  62. $this->flagDirectives[$directive] = $response->headers->hasCacheControlDirective($directive);
  63. }
  64. }
  65. $age = $response->getAge();
  66. $this->age = max($this->age, $age);
  67. if ($this->willMakeFinalResponseUncacheable($response)) {
  68. $this->isNotCacheableResponseEmbedded = true;
  69. return;
  70. }
  71. $maxAge = $response->headers->hasCacheControlDirective('max-age') ? (int) $response->headers->getCacheControlDirective('max-age') : null;
  72. $sharedMaxAge = $response->headers->hasCacheControlDirective('s-maxage') ? (int) $response->headers->getCacheControlDirective('s-maxage') : $maxAge;
  73. $expires = $response->getExpires();
  74. $expires = null !== $expires ? (int) $expires->format('U') - (int) $response->getDate()->format('U') : null;
  75. // See https://datatracker.ietf.org/doc/html/rfc7234#section-4.2.2
  76. // If a response is "public" but does not have maximum lifetime, heuristics might be applied.
  77. // Do not store NULL values so the final response can have more limiting value from other responses.
  78. $isHeuristicallyCacheable = $response->headers->hasCacheControlDirective('public')
  79. && null === $maxAge
  80. && null === $sharedMaxAge
  81. && null === $expires;
  82. if (!$isHeuristicallyCacheable || null !== $maxAge || null !== $expires) {
  83. $this->storeRelativeAgeDirective('max-age', $maxAge, $expires, $age);
  84. }
  85. if (!$isHeuristicallyCacheable || null !== $sharedMaxAge || null !== $expires) {
  86. $this->storeRelativeAgeDirective('s-maxage', $sharedMaxAge, $expires, $age);
  87. }
  88. if (null !== $expires) {
  89. $this->ageDirectives['expires'] = true;
  90. }
  91. }
  92. /**
  93. * {@inheritdoc}
  94. */
  95. public function update(Response $response)
  96. {
  97. // if we have no embedded Response, do nothing
  98. if (0 === $this->embeddedResponses) {
  99. return;
  100. }
  101. // Remove validation related headers of the final response,
  102. // because some of the response content comes from at least
  103. // one embedded response (which likely has a different caching strategy).
  104. $response->setEtag(null);
  105. $response->setLastModified(null);
  106. $this->add($response);
  107. $response->headers->set('Age', $this->age);
  108. if ($this->isNotCacheableResponseEmbedded) {
  109. if ($this->flagDirectives['no-store']) {
  110. $response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');
  111. } else {
  112. $response->headers->set('Cache-Control', 'no-cache, must-revalidate');
  113. }
  114. return;
  115. }
  116. $flags = array_filter($this->flagDirectives);
  117. if (isset($flags['must-revalidate'])) {
  118. $flags['no-cache'] = true;
  119. }
  120. $response->headers->set('Cache-Control', implode(', ', array_keys($flags)));
  121. $maxAge = null;
  122. if (is_numeric($this->ageDirectives['max-age'])) {
  123. $maxAge = $this->ageDirectives['max-age'] + $this->age;
  124. $response->headers->addCacheControlDirective('max-age', $maxAge);
  125. }
  126. if (is_numeric($this->ageDirectives['s-maxage'])) {
  127. $sMaxage = $this->ageDirectives['s-maxage'] + $this->age;
  128. if ($maxAge !== $sMaxage) {
  129. $response->headers->addCacheControlDirective('s-maxage', $sMaxage);
  130. }
  131. }
  132. if ($this->ageDirectives['expires'] && null !== $maxAge) {
  133. $date = clone $response->getDate();
  134. $date = $date->modify('+'.$maxAge.' seconds');
  135. $response->setExpires($date);
  136. }
  137. }
  138. /**
  139. * RFC2616, Section 13.4.
  140. *
  141. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
  142. */
  143. private function willMakeFinalResponseUncacheable(Response $response): bool
  144. {
  145. // RFC2616: A response received with a status code of 200, 203, 300, 301 or 410
  146. // MAY be stored by a cache […] unless a cache-control directive prohibits caching.
  147. if ($response->headers->hasCacheControlDirective('no-cache')
  148. || $response->headers->getCacheControlDirective('no-store')
  149. ) {
  150. return true;
  151. }
  152. // Last-Modified and Etag headers cannot be merged, they render the response uncacheable
  153. // by default (except if the response also has max-age etc.).
  154. if (\in_array($response->getStatusCode(), [200, 203, 300, 301, 410])
  155. && null === $response->getLastModified()
  156. && null === $response->getEtag()
  157. ) {
  158. return false;
  159. }
  160. // RFC2616: A response received with any other status code (e.g. status codes 302 and 307)
  161. // MUST NOT be returned in a reply to a subsequent request unless there are
  162. // cache-control directives or another header(s) that explicitly allow it.
  163. $cacheControl = ['max-age', 's-maxage', 'must-revalidate', 'proxy-revalidate', 'public', 'private'];
  164. foreach ($cacheControl as $key) {
  165. if ($response->headers->hasCacheControlDirective($key)) {
  166. return false;
  167. }
  168. }
  169. if ($response->headers->has('Expires')) {
  170. return false;
  171. }
  172. return true;
  173. }
  174. /**
  175. * Store lowest max-age/s-maxage/expires for the final response.
  176. *
  177. * The response might have been stored in cache a while ago. To keep things comparable,
  178. * we have to subtract the age so that the value is normalized for an age of 0.
  179. *
  180. * If the value is lower than the currently stored value, we update the value, to keep a rolling
  181. * minimal value of each instruction. If the value is NULL, the directive will not be set on the final response.
  182. */
  183. private function storeRelativeAgeDirective(string $directive, ?int $value, ?int $expires, int $age): void
  184. {
  185. if (null === $value && null === $expires) {
  186. $this->ageDirectives[$directive] = false;
  187. }
  188. if (false !== $this->ageDirectives[$directive]) {
  189. $value = min($value ?? PHP_INT_MAX, $expires ?? PHP_INT_MAX);
  190. $value -= $age;
  191. $this->ageDirectives[$directive] = null !== $this->ageDirectives[$directive] ? min($this->ageDirectives[$directive], $value) : $value;
  192. }
  193. }
  194. }