HeaderBag.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. class HeaderBag implements \IteratorAggregate, \Countable
  17. {
  18. protected $headers = array();
  19. protected $cacheControl = array();
  20. /**
  21. * @param array $headers An array of HTTP headers
  22. */
  23. public function __construct(array $headers = array())
  24. {
  25. foreach ($headers as $key => $values) {
  26. $this->set($key, $values);
  27. }
  28. }
  29. /**
  30. * Returns the headers as a string.
  31. *
  32. * @return string The headers
  33. */
  34. public function __toString()
  35. {
  36. if (!$this->headers) {
  37. return '';
  38. }
  39. $max = max(array_map('strlen', array_keys($this->headers))) + 1;
  40. $content = '';
  41. ksort($this->headers);
  42. foreach ($this->headers as $name => $values) {
  43. $name = implode('-', array_map('ucfirst', explode('-', $name)));
  44. foreach ($values as $value) {
  45. $content .= sprintf("%-{$max}s %s\r\n", $name.':', $value);
  46. }
  47. }
  48. return $content;
  49. }
  50. /**
  51. * Returns the headers.
  52. *
  53. * @return array An array of headers
  54. */
  55. public function all()
  56. {
  57. return $this->headers;
  58. }
  59. /**
  60. * Returns the parameter keys.
  61. *
  62. * @return array An array of parameter keys
  63. */
  64. public function keys()
  65. {
  66. return array_keys($this->headers);
  67. }
  68. /**
  69. * Replaces the current HTTP headers by a new set.
  70. *
  71. * @param array $headers An array of HTTP headers
  72. */
  73. public function replace(array $headers = array())
  74. {
  75. $this->headers = array();
  76. $this->add($headers);
  77. }
  78. /**
  79. * Adds new headers the current HTTP headers set.
  80. *
  81. * @param array $headers An array of HTTP headers
  82. */
  83. public function add(array $headers)
  84. {
  85. foreach ($headers as $key => $values) {
  86. $this->set($key, $values);
  87. }
  88. }
  89. /**
  90. * Returns a header value by name.
  91. *
  92. * @param string $key The header name
  93. * @param string|string[]|null $default The default value
  94. * @param bool $first Whether to return the first value or all header values
  95. *
  96. * @return string|string[]|null The first header value or default value if $first is true, an array of values otherwise
  97. */
  98. public function get($key, $default = null, $first = true)
  99. {
  100. $key = str_replace('_', '-', strtolower($key));
  101. if (!array_key_exists($key, $this->headers)) {
  102. if (null === $default) {
  103. return $first ? null : array();
  104. }
  105. return $first ? $default : array($default);
  106. }
  107. if ($first) {
  108. return \count($this->headers[$key]) ? $this->headers[$key][0] : $default;
  109. }
  110. return $this->headers[$key];
  111. }
  112. /**
  113. * Sets a header by name.
  114. *
  115. * @param string $key The key
  116. * @param string|string[] $values The value or an array of values
  117. * @param bool $replace Whether to replace the actual value or not (true by default)
  118. */
  119. public function set($key, $values, $replace = true)
  120. {
  121. $key = str_replace('_', '-', strtolower($key));
  122. $values = array_values((array) $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. if ('cache-control' === $key) {
  129. $this->cacheControl = $this->parseCacheControl(implode(', ', $this->headers[$key]));
  130. }
  131. }
  132. /**
  133. * Returns true if the HTTP header is defined.
  134. *
  135. * @param string $key The HTTP header
  136. *
  137. * @return bool true if the parameter exists, false otherwise
  138. */
  139. public function has($key)
  140. {
  141. return array_key_exists(str_replace('_', '-', strtolower($key)), $this->headers);
  142. }
  143. /**
  144. * Returns true if the given HTTP header contains the given value.
  145. *
  146. * @param string $key The HTTP header name
  147. * @param string $value The HTTP value
  148. *
  149. * @return bool true if the value is contained in the header, false otherwise
  150. */
  151. public function contains($key, $value)
  152. {
  153. return \in_array($value, $this->get($key, null, false));
  154. }
  155. /**
  156. * Removes a header.
  157. *
  158. * @param string $key The HTTP header name
  159. */
  160. public function remove($key)
  161. {
  162. $key = str_replace('_', '-', strtolower($key));
  163. unset($this->headers[$key]);
  164. if ('cache-control' === $key) {
  165. $this->cacheControl = array();
  166. }
  167. }
  168. /**
  169. * Returns the HTTP header value converted to a date.
  170. *
  171. * @param string $key The parameter key
  172. * @param \DateTime $default The default value
  173. *
  174. * @return \DateTime|null The parsed DateTime or the default value if the header does not exist
  175. *
  176. * @throws \RuntimeException When the HTTP header is not parseable
  177. */
  178. public function getDate($key, \DateTime $default = null)
  179. {
  180. if (null === $value = $this->get($key)) {
  181. return $default;
  182. }
  183. if (false === $date = \DateTime::createFromFormat(DATE_RFC2822, $value)) {
  184. throw new \RuntimeException(sprintf('The %s HTTP header is not parseable (%s).', $key, $value));
  185. }
  186. return $date;
  187. }
  188. /**
  189. * Adds a custom Cache-Control directive.
  190. *
  191. * @param string $key The Cache-Control directive name
  192. * @param mixed $value The Cache-Control directive value
  193. */
  194. public function addCacheControlDirective($key, $value = true)
  195. {
  196. $this->cacheControl[$key] = $value;
  197. $this->set('Cache-Control', $this->getCacheControlHeader());
  198. }
  199. /**
  200. * Returns true if the Cache-Control directive is defined.
  201. *
  202. * @param string $key The Cache-Control directive
  203. *
  204. * @return bool true if the directive exists, false otherwise
  205. */
  206. public function hasCacheControlDirective($key)
  207. {
  208. return array_key_exists($key, $this->cacheControl);
  209. }
  210. /**
  211. * Returns a Cache-Control directive value by name.
  212. *
  213. * @param string $key The directive name
  214. *
  215. * @return mixed|null The directive value if defined, null otherwise
  216. */
  217. public function getCacheControlDirective($key)
  218. {
  219. return array_key_exists($key, $this->cacheControl) ? $this->cacheControl[$key] : null;
  220. }
  221. /**
  222. * Removes a Cache-Control directive.
  223. *
  224. * @param string $key The Cache-Control directive
  225. */
  226. public function removeCacheControlDirective($key)
  227. {
  228. unset($this->cacheControl[$key]);
  229. $this->set('Cache-Control', $this->getCacheControlHeader());
  230. }
  231. /**
  232. * Returns an iterator for headers.
  233. *
  234. * @return \ArrayIterator An \ArrayIterator instance
  235. */
  236. public function getIterator()
  237. {
  238. return new \ArrayIterator($this->headers);
  239. }
  240. /**
  241. * Returns the number of headers.
  242. *
  243. * @return int The number of headers
  244. */
  245. public function count()
  246. {
  247. return \count($this->headers);
  248. }
  249. protected function getCacheControlHeader()
  250. {
  251. $parts = array();
  252. ksort($this->cacheControl);
  253. foreach ($this->cacheControl as $key => $value) {
  254. if (true === $value) {
  255. $parts[] = $key;
  256. } else {
  257. if (preg_match('#[^a-zA-Z0-9._-]#', $value)) {
  258. $value = '"'.$value.'"';
  259. }
  260. $parts[] = "$key=$value";
  261. }
  262. }
  263. return implode(', ', $parts);
  264. }
  265. /**
  266. * Parses a Cache-Control HTTP header.
  267. *
  268. * @param string $header The value of the Cache-Control HTTP header
  269. *
  270. * @return array An array representing the attribute values
  271. */
  272. protected function parseCacheControl($header)
  273. {
  274. $cacheControl = array();
  275. preg_match_all('#([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?#', $header, $matches, PREG_SET_ORDER);
  276. foreach ($matches as $match) {
  277. $cacheControl[strtolower($match[1])] = isset($match[3]) ? $match[3] : (isset($match[2]) ? $match[2] : true);
  278. }
  279. return $cacheControl;
  280. }
  281. }