HeaderBag.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 (!$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 = 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->all());
  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. $headers = $this->all();
  104. if (!array_key_exists($key, $headers)) {
  105. if (null === $default) {
  106. return $first ? null : array();
  107. }
  108. return $first ? $default : array($default);
  109. }
  110. if ($first) {
  111. return count($headers[$key]) ? $headers[$key][0] : $default;
  112. }
  113. return $headers[$key];
  114. }
  115. /**
  116. * Sets a header by name.
  117. *
  118. * @param string $key The key
  119. * @param string|array $values The value or an array of values
  120. * @param bool $replace Whether to replace the actual value or not (true by default)
  121. */
  122. public function set($key, $values, $replace = true)
  123. {
  124. $key = str_replace('_', '-', strtolower($key));
  125. $values = array_values((array) $values);
  126. if (true === $replace || !isset($this->headers[$key])) {
  127. $this->headers[$key] = $values;
  128. } else {
  129. $this->headers[$key] = array_merge($this->headers[$key], $values);
  130. }
  131. if ('cache-control' === $key) {
  132. $this->cacheControl = $this->parseCacheControl($values[0]);
  133. }
  134. }
  135. /**
  136. * Returns true if the HTTP header is defined.
  137. *
  138. * @param string $key The HTTP header
  139. *
  140. * @return bool true if the parameter exists, false otherwise
  141. */
  142. public function has($key)
  143. {
  144. return array_key_exists(str_replace('_', '-', strtolower($key)), $this->all());
  145. }
  146. /**
  147. * Returns true if the given HTTP header contains the given value.
  148. *
  149. * @param string $key The HTTP header name
  150. * @param string $value The HTTP value
  151. *
  152. * @return bool true if the value is contained in the header, false otherwise
  153. */
  154. public function contains($key, $value)
  155. {
  156. return in_array($value, $this->get($key, null, false));
  157. }
  158. /**
  159. * Removes a header.
  160. *
  161. * @param string $key The HTTP header name
  162. */
  163. public function remove($key)
  164. {
  165. $key = str_replace('_', '-', strtolower($key));
  166. unset($this->headers[$key]);
  167. if ('cache-control' === $key) {
  168. $this->cacheControl = array();
  169. }
  170. }
  171. /**
  172. * Returns the HTTP header value converted to a date.
  173. *
  174. * @param string $key The parameter key
  175. * @param \DateTime $default The default value
  176. *
  177. * @return null|\DateTime The parsed DateTime or the default value if the header does not exist
  178. *
  179. * @throws \RuntimeException When the HTTP header is not parseable
  180. */
  181. public function getDate($key, \DateTime $default = null)
  182. {
  183. if (null === $value = $this->get($key)) {
  184. return $default;
  185. }
  186. if (false === $date = \DateTime::createFromFormat(DATE_RFC2822, $value)) {
  187. throw new \RuntimeException(sprintf('The %s HTTP header is not parseable (%s).', $key, $value));
  188. }
  189. return $date;
  190. }
  191. /**
  192. * Adds a custom Cache-Control directive.
  193. *
  194. * @param string $key The Cache-Control directive name
  195. * @param mixed $value The Cache-Control directive value
  196. */
  197. public function addCacheControlDirective($key, $value = true)
  198. {
  199. $this->cacheControl[$key] = $value;
  200. $this->set('Cache-Control', $this->getCacheControlHeader());
  201. }
  202. /**
  203. * Returns true if the Cache-Control directive is defined.
  204. *
  205. * @param string $key The Cache-Control directive
  206. *
  207. * @return bool true if the directive exists, false otherwise
  208. */
  209. public function hasCacheControlDirective($key)
  210. {
  211. return array_key_exists($key, $this->cacheControl);
  212. }
  213. /**
  214. * Returns a Cache-Control directive value by name.
  215. *
  216. * @param string $key The directive name
  217. *
  218. * @return mixed|null The directive value if defined, null otherwise
  219. */
  220. public function getCacheControlDirective($key)
  221. {
  222. return array_key_exists($key, $this->cacheControl) ? $this->cacheControl[$key] : null;
  223. }
  224. /**
  225. * Removes a Cache-Control directive.
  226. *
  227. * @param string $key The Cache-Control directive
  228. */
  229. public function removeCacheControlDirective($key)
  230. {
  231. unset($this->cacheControl[$key]);
  232. $this->set('Cache-Control', $this->getCacheControlHeader());
  233. }
  234. /**
  235. * Returns an iterator for headers.
  236. *
  237. * @return \ArrayIterator An \ArrayIterator instance
  238. */
  239. public function getIterator()
  240. {
  241. return new \ArrayIterator($this->headers);
  242. }
  243. /**
  244. * Returns the number of headers.
  245. *
  246. * @return int The number of headers
  247. */
  248. public function count()
  249. {
  250. return count($this->headers);
  251. }
  252. protected function getCacheControlHeader()
  253. {
  254. $parts = array();
  255. ksort($this->cacheControl);
  256. foreach ($this->cacheControl as $key => $value) {
  257. if (true === $value) {
  258. $parts[] = $key;
  259. } else {
  260. if (preg_match('#[^a-zA-Z0-9._-]#', $value)) {
  261. $value = '"'.$value.'"';
  262. }
  263. $parts[] = "$key=$value";
  264. }
  265. }
  266. return implode(', ', $parts);
  267. }
  268. /**
  269. * Parses a Cache-Control HTTP header.
  270. *
  271. * @param string $header The value of the Cache-Control HTTP header
  272. *
  273. * @return array An array representing the attribute values
  274. */
  275. protected function parseCacheControl($header)
  276. {
  277. $cacheControl = array();
  278. preg_match_all('#([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?#', $header, $matches, PREG_SET_ORDER);
  279. foreach ($matches as $match) {
  280. $cacheControl[strtolower($match[1])] = isset($match[3]) ? $match[3] : (isset($match[2]) ? $match[2] : true);
  281. }
  282. return $cacheControl;
  283. }
  284. }