19 class HeaderBag implements \IteratorAggregate, \Countable
31 foreach (
$headers as $key => $values) {
32 $this->
set($key, $values);
48 $max = max(array_map(
'strlen', array_keys(
$headers))) + 1;
50 foreach (
$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);
77 return array_keys($this->
all());
87 $this->headers = array();
98 foreach (
$headers as $key => $values) {
99 $this->
set($key, $values);
112 public function get($key, $default =
null, $first =
true)
114 $key = str_replace(
'_',
'-', strtolower($key));
117 if (!array_key_exists($key,
$headers)) {
118 if (
null === $default) {
119 return $first ? null : array();
122 return $first ? $default : array($default);
139 public function set($key, $values, $replace =
true)
141 $key = str_replace(
'_',
'-', strtolower($key));
143 $values = array_values((array) $values);
145 if (
true === $replace || !isset($this->headers[$key])) {
146 $this->headers[$key] = $values;
148 $this->headers[$key] = array_merge($this->headers[$key], $values);
151 if (
'cache-control' === $key) {
165 return array_key_exists(str_replace(
'_',
'-', strtolower($key)), $this->
all());
178 return in_array($value, $this->
get($key,
null,
false));
186 public function remove($key)
188 $key = str_replace(
'_',
'-', strtolower($key));
190 unset($this->headers[$key]);
192 if (
'cache-control' === $key) {
193 $this->cacheControl = array();
207 public function getDate($key, \DateTime $default =
null)
209 if (
null === $value = $this->
get($key)) {
213 if (
false === $date = \DateTime::createFromFormat(DATE_RFC2822, $value)) {
214 throw new \RuntimeException(sprintf(
'The %s HTTP header is not parseable (%s).', $key, $value));
228 $this->cacheControl[$key] = $value;
242 return array_key_exists($key, $this->cacheControl);
254 return array_key_exists($key, $this->cacheControl) ? $this->cacheControl[$key] :
null;
264 unset($this->cacheControl[$key]);
276 return new \ArrayIterator($this->headers);
286 return count($this->headers);
292 ksort($this->cacheControl);
293 foreach ($this->cacheControl as $key => $value) {
294 if (
true === $value) {
297 if (preg_match(
'#[^a-zA-Z0-9._-]#', $value)) {
298 $value =
'"'.$value.
'"';
301 $parts[] =
"$key=$value";
305 return implode(
', ', $parts);
318 preg_match_all(
'#([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?#', $header, $matches, PREG_SET_ORDER);
319 foreach ($matches as $match) {
320 $cacheControl[strtolower($match[1])] = isset($match[3]) ? $match[3] : (isset($match[2]) ? $match[2] :
true);