HeaderBag.php 7.3 KB

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