ResponseHeaderBag.php 8.3 KB

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