HeaderBag.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. * HeaderBag is a container for HTTP headers.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. *
  16. * @implements \IteratorAggregate<string, list<string|null>>
  17. */
  18. class HeaderBag implements \IteratorAggregate, \Countable, \Stringable
  19. {
  20. protected const UPPER = '_ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  21. protected const LOWER = '-abcdefghijklmnopqrstuvwxyz';
  22. /**
  23. * @var array<string, list<string|null>>
  24. */
  25. protected $headers = [];
  26. protected $cacheControl = [];
  27. public function __construct(array $headers = [])
  28. {
  29. foreach ($headers as $key => $values) {
  30. $this->set($key, $values);
  31. }
  32. }
  33. /**
  34. * Returns the headers as a string.
  35. */
  36. public function __toString(): string
  37. {
  38. if (!$headers = $this->all()) {
  39. return '';
  40. }
  41. ksort($headers);
  42. $max = max(array_map('strlen', array_keys($headers))) + 1;
  43. $content = '';
  44. foreach ($headers as $name => $values) {
  45. $name = ucwords($name, '-');
  46. foreach ($values as $value) {
  47. $content .= sprintf("%-{$max}s %s\r\n", $name.':', $value);
  48. }
  49. }
  50. return $content;
  51. }
  52. /**
  53. * Returns the headers.
  54. *
  55. * @param string|null $key The name of the headers to return or null to get them all
  56. *
  57. * @return ($key is null ? array<string, list<string|null>> : list<string|null>)
  58. */
  59. public function all(?string $key = null): array
  60. {
  61. if (null !== $key) {
  62. return $this->headers[strtr($key, self::UPPER, self::LOWER)] ?? [];
  63. }
  64. return $this->headers;
  65. }
  66. /**
  67. * Returns the parameter keys.
  68. *
  69. * @return string[]
  70. */
  71. public function keys(): array
  72. {
  73. return array_keys($this->all());
  74. }
  75. /**
  76. * Replaces the current HTTP headers by a new set.
  77. *
  78. * @return void
  79. */
  80. public function replace(array $headers = [])
  81. {
  82. $this->headers = [];
  83. $this->add($headers);
  84. }
  85. /**
  86. * Adds new headers the current HTTP headers set.
  87. *
  88. * @return void
  89. */
  90. public function add(array $headers)
  91. {
  92. foreach ($headers as $key => $values) {
  93. $this->set($key, $values);
  94. }
  95. }
  96. /**
  97. * Returns the first header by name or the default one.
  98. */
  99. public function get(string $key, ?string $default = null): ?string
  100. {
  101. $headers = $this->all($key);
  102. if (!$headers) {
  103. return $default;
  104. }
  105. if (null === $headers[0]) {
  106. return null;
  107. }
  108. return (string) $headers[0];
  109. }
  110. /**
  111. * Sets a header by name.
  112. *
  113. * @param string|string[]|null $values The value or an array of values
  114. * @param bool $replace Whether to replace the actual value or not (true by default)
  115. *
  116. * @return void
  117. */
  118. public function set(string $key, string|array|null $values, bool $replace = true)
  119. {
  120. $key = strtr($key, self::UPPER, self::LOWER);
  121. if (\is_array($values)) {
  122. $values = array_values($values);
  123. if (true === $replace || !isset($this->headers[$key])) {
  124. $this->headers[$key] = $values;
  125. } else {
  126. $this->headers[$key] = array_merge($this->headers[$key], $values);
  127. }
  128. } else {
  129. if (true === $replace || !isset($this->headers[$key])) {
  130. $this->headers[$key] = [$values];
  131. } else {
  132. $this->headers[$key][] = $values;
  133. }
  134. }
  135. if ('cache-control' === $key) {
  136. $this->cacheControl = $this->parseCacheControl(implode(', ', $this->headers[$key]));
  137. }
  138. }
  139. /**
  140. * Returns true if the HTTP header is defined.
  141. */
  142. public function has(string $key): bool
  143. {
  144. return \array_key_exists(strtr($key, self::UPPER, self::LOWER), $this->all());
  145. }
  146. /**
  147. * Returns true if the given HTTP header contains the given value.
  148. */
  149. public function contains(string $key, string $value): bool
  150. {
  151. return \in_array($value, $this->all($key));
  152. }
  153. /**
  154. * Removes a header.
  155. *
  156. * @return void
  157. */
  158. public function remove(string $key)
  159. {
  160. $key = strtr($key, self::UPPER, self::LOWER);
  161. unset($this->headers[$key]);
  162. if ('cache-control' === $key) {
  163. $this->cacheControl = [];
  164. }
  165. }
  166. /**
  167. * Returns the HTTP header value converted to a date.
  168. *
  169. * @return \DateTimeImmutable|null
  170. *
  171. * @throws \RuntimeException When the HTTP header is not parseable
  172. */
  173. public function getDate(string $key, ?\DateTimeInterface $default = null): ?\DateTimeInterface
  174. {
  175. if (null === $value = $this->get($key)) {
  176. return null !== $default ? \DateTimeImmutable::createFromInterface($default) : null;
  177. }
  178. if (false === $date = \DateTimeImmutable::createFromFormat(\DATE_RFC2822, $value)) {
  179. throw new \RuntimeException(sprintf('The "%s" HTTP header is not parseable (%s).', $key, $value));
  180. }
  181. return $date;
  182. }
  183. /**
  184. * Adds a custom Cache-Control directive.
  185. *
  186. * @return void
  187. */
  188. public function addCacheControlDirective(string $key, bool|string $value = true)
  189. {
  190. $this->cacheControl[$key] = $value;
  191. $this->set('Cache-Control', $this->getCacheControlHeader());
  192. }
  193. /**
  194. * Returns true if the Cache-Control directive is defined.
  195. */
  196. public function hasCacheControlDirective(string $key): bool
  197. {
  198. return \array_key_exists($key, $this->cacheControl);
  199. }
  200. /**
  201. * Returns a Cache-Control directive value by name.
  202. */
  203. public function getCacheControlDirective(string $key): bool|string|null
  204. {
  205. return $this->cacheControl[$key] ?? null;
  206. }
  207. /**
  208. * Removes a Cache-Control directive.
  209. *
  210. * @return void
  211. */
  212. public function removeCacheControlDirective(string $key)
  213. {
  214. unset($this->cacheControl[$key]);
  215. $this->set('Cache-Control', $this->getCacheControlHeader());
  216. }
  217. /**
  218. * Returns an iterator for headers.
  219. *
  220. * @return \ArrayIterator<string, list<string|null>>
  221. */
  222. public function getIterator(): \ArrayIterator
  223. {
  224. return new \ArrayIterator($this->headers);
  225. }
  226. /**
  227. * Returns the number of headers.
  228. */
  229. public function count(): int
  230. {
  231. return \count($this->headers);
  232. }
  233. /**
  234. * @return string
  235. */
  236. protected function getCacheControlHeader()
  237. {
  238. ksort($this->cacheControl);
  239. return HeaderUtils::toString($this->cacheControl, ',');
  240. }
  241. /**
  242. * Parses a Cache-Control HTTP header.
  243. */
  244. protected function parseCacheControl(string $header): array
  245. {
  246. $parts = HeaderUtils::split($header, ',=');
  247. return HeaderUtils::combine($parts);
  248. }
  249. }