ResponseHeaderBag.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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\HttpFoundation;
  11. /**
  12. * ResponseHeaderBag is a container for Response HTTP headers.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class ResponseHeaderBag extends HeaderBag
  17. {
  18. public const COOKIES_FLAT = 'flat';
  19. public const COOKIES_ARRAY = 'array';
  20. public const DISPOSITION_ATTACHMENT = 'attachment';
  21. public const DISPOSITION_INLINE = 'inline';
  22. protected $computedCacheControl = [];
  23. protected $cookies = [];
  24. protected $headerNames = [];
  25. public function __construct(array $headers = [])
  26. {
  27. parent::__construct($headers);
  28. if (!isset($this->headers['cache-control'])) {
  29. $this->set('Cache-Control', '');
  30. }
  31. /* RFC2616 - 14.18 says all Responses need to have a Date */
  32. if (!isset($this->headers['date'])) {
  33. $this->initDate();
  34. }
  35. }
  36. /**
  37. * Returns the headers, with original capitalizations.
  38. */
  39. public function allPreserveCase(): array
  40. {
  41. $headers = [];
  42. foreach ($this->all() as $name => $value) {
  43. $headers[$this->headerNames[$name] ?? $name] = $value;
  44. }
  45. return $headers;
  46. }
  47. /**
  48. * @return array
  49. */
  50. public function allPreserveCaseWithoutCookies()
  51. {
  52. $headers = $this->allPreserveCase();
  53. if (isset($this->headerNames['set-cookie'])) {
  54. unset($headers[$this->headerNames['set-cookie']]);
  55. }
  56. return $headers;
  57. }
  58. /**
  59. * @return void
  60. */
  61. public function replace(array $headers = [])
  62. {
  63. $this->headerNames = [];
  64. parent::replace($headers);
  65. if (!isset($this->headers['cache-control'])) {
  66. $this->set('Cache-Control', '');
  67. }
  68. if (!isset($this->headers['date'])) {
  69. $this->initDate();
  70. }
  71. }
  72. public function all(?string $key = null): array
  73. {
  74. $headers = parent::all();
  75. if (null !== $key) {
  76. $key = strtr($key, self::UPPER, self::LOWER);
  77. return 'set-cookie' !== $key ? $headers[$key] ?? [] : array_map('strval', $this->getCookies());
  78. }
  79. foreach ($this->getCookies() as $cookie) {
  80. $headers['set-cookie'][] = (string) $cookie;
  81. }
  82. return $headers;
  83. }
  84. /**
  85. * @return void
  86. */
  87. public function set(string $key, string|array|null $values, bool $replace = true)
  88. {
  89. $uniqueKey = strtr($key, self::UPPER, self::LOWER);
  90. if ('set-cookie' === $uniqueKey) {
  91. if ($replace) {
  92. $this->cookies = [];
  93. }
  94. foreach ((array) $values as $cookie) {
  95. $this->setCookie(Cookie::fromString($cookie));
  96. }
  97. $this->headerNames[$uniqueKey] = $key;
  98. return;
  99. }
  100. $this->headerNames[$uniqueKey] = $key;
  101. parent::set($key, $values, $replace);
  102. // ensure the cache-control header has sensible defaults
  103. if (\in_array($uniqueKey, ['cache-control', 'etag', 'last-modified', 'expires'], true) && '' !== $computed = $this->computeCacheControlValue()) {
  104. $this->headers['cache-control'] = [$computed];
  105. $this->headerNames['cache-control'] = 'Cache-Control';
  106. $this->computedCacheControl = $this->parseCacheControl($computed);
  107. }
  108. }
  109. /**
  110. * @return void
  111. */
  112. public function remove(string $key)
  113. {
  114. $uniqueKey = strtr($key, self::UPPER, self::LOWER);
  115. unset($this->headerNames[$uniqueKey]);
  116. if ('set-cookie' === $uniqueKey) {
  117. $this->cookies = [];
  118. return;
  119. }
  120. parent::remove($key);
  121. if ('cache-control' === $uniqueKey) {
  122. $this->computedCacheControl = [];
  123. }
  124. if ('date' === $uniqueKey) {
  125. $this->initDate();
  126. }
  127. }
  128. public function hasCacheControlDirective(string $key): bool
  129. {
  130. return \array_key_exists($key, $this->computedCacheControl);
  131. }
  132. public function getCacheControlDirective(string $key): bool|string|null
  133. {
  134. return $this->computedCacheControl[$key] ?? null;
  135. }
  136. /**
  137. * @return void
  138. */
  139. public function setCookie(Cookie $cookie)
  140. {
  141. $this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;
  142. $this->headerNames['set-cookie'] = 'Set-Cookie';
  143. }
  144. /**
  145. * Removes a cookie from the array, but does not unset it in the browser.
  146. *
  147. * @return void
  148. */
  149. public function removeCookie(string $name, ?string $path = '/', ?string $domain = null)
  150. {
  151. $path ??= '/';
  152. unset($this->cookies[$domain][$path][$name]);
  153. if (empty($this->cookies[$domain][$path])) {
  154. unset($this->cookies[$domain][$path]);
  155. if (empty($this->cookies[$domain])) {
  156. unset($this->cookies[$domain]);
  157. }
  158. }
  159. if (empty($this->cookies)) {
  160. unset($this->headerNames['set-cookie']);
  161. }
  162. }
  163. /**
  164. * Returns an array with all cookies.
  165. *
  166. * @return Cookie[]
  167. *
  168. * @throws \InvalidArgumentException When the $format is invalid
  169. */
  170. public function getCookies(string $format = self::COOKIES_FLAT): array
  171. {
  172. if (!\in_array($format, [self::COOKIES_FLAT, self::COOKIES_ARRAY])) {
  173. throw new \InvalidArgumentException(sprintf('Format "%s" invalid (%s).', $format, implode(', ', [self::COOKIES_FLAT, self::COOKIES_ARRAY])));
  174. }
  175. if (self::COOKIES_ARRAY === $format) {
  176. return $this->cookies;
  177. }
  178. $flattenedCookies = [];
  179. foreach ($this->cookies as $path) {
  180. foreach ($path as $cookies) {
  181. foreach ($cookies as $cookie) {
  182. $flattenedCookies[] = $cookie;
  183. }
  184. }
  185. }
  186. return $flattenedCookies;
  187. }
  188. /**
  189. * Clears a cookie in the browser.
  190. *
  191. * @param bool $partitioned
  192. *
  193. * @return void
  194. */
  195. public function clearCookie(string $name, ?string $path = '/', ?string $domain = null, bool $secure = false, bool $httpOnly = true, ?string $sameSite = null /* , bool $partitioned = false */)
  196. {
  197. $partitioned = 6 < \func_num_args() ? \func_get_arg(6) : false;
  198. $this->setCookie(new Cookie($name, null, 1, $path, $domain, $secure, $httpOnly, false, $sameSite, $partitioned));
  199. }
  200. /**
  201. * @see HeaderUtils::makeDisposition()
  202. *
  203. * @return string
  204. */
  205. public function makeDisposition(string $disposition, string $filename, string $filenameFallback = '')
  206. {
  207. return HeaderUtils::makeDisposition($disposition, $filename, $filenameFallback);
  208. }
  209. /**
  210. * Returns the calculated value of the cache-control header.
  211. *
  212. * This considers several other headers and calculates or modifies the
  213. * cache-control header to a sensible, conservative value.
  214. */
  215. protected function computeCacheControlValue(): string
  216. {
  217. if (!$this->cacheControl) {
  218. if ($this->has('Last-Modified') || $this->has('Expires')) {
  219. return 'private, must-revalidate'; // allows for heuristic expiration (RFC 7234 Section 4.2.2) in the case of "Last-Modified"
  220. }
  221. // conservative by default
  222. return 'no-cache, private';
  223. }
  224. $header = $this->getCacheControlHeader();
  225. if (isset($this->cacheControl['public']) || isset($this->cacheControl['private'])) {
  226. return $header;
  227. }
  228. // public if s-maxage is defined, private otherwise
  229. if (!isset($this->cacheControl['s-maxage'])) {
  230. return $header.', private';
  231. }
  232. return $header;
  233. }
  234. private function initDate(): void
  235. {
  236. $this->set('Date', gmdate('D, d M Y H:i:s').' GMT');
  237. }
  238. }