HeaderBag.php 8.5 KB

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