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