19 class HeaderBag
implements \IteratorAggregate, \Countable
21 protected const UPPER =
'_ABCDEFGHIJKLMNOPQRSTUVWXYZ';
22 protected const LOWER =
'-abcdefghijklmnopqrstuvwxyz';
29 foreach (
$headers as $key => $values) {
30 $this->
set($key, $values);
46 $max = max(array_map(
'strlen', array_keys(
$headers))) + 1;
48 foreach (
$headers as $name => $values) {
49 $name = ucwords($name,
'-');
50 foreach ($values as $value) {
51 $content .= sprintf(
"%-{$max}s %s\r\n", $name.
':', $value);
67 if (1 <= \func_num_args() &&
null !== $key = func_get_arg(0)) {
68 return $this->headers[strtr($key, self::UPPER, self::LOWER)] ?? [];
81 return array_keys($this->
all());
98 foreach (
$headers as $key => $values) {
99 $this->
set($key, $values);
111 public function get($key, $default =
null)
114 if (2 < \func_num_args()) {
115 @trigger_error(sprintf(
'Passing a third argument to "%s()" is deprecated since Symfony 4.4, use method "all()" instead', __METHOD__), E_USER_DEPRECATED);
117 if (!func_get_arg(2)) {
140 public function set($key, $values, $replace =
true)
142 $key = strtr($key, self::UPPER, self::LOWER);
144 if (\is_array($values)) {
145 $values = array_values($values);
147 if (
true === $replace || !isset($this->headers[$key])) {
148 $this->headers[$key] = $values;
150 $this->headers[$key] = array_merge($this->headers[$key], $values);
153 if (
true === $replace || !isset($this->headers[$key])) {
154 $this->headers[$key] = [$values];
156 $this->headers[$key][] = $values;
160 if (
'cache-control' === $key) {
161 $this->cacheControl = $this->
parseCacheControl(implode(
', ', $this->headers[$key]));
174 return \array_key_exists(strtr($key, self::UPPER, self::LOWER), $this->
all());
187 return \in_array($value, $this->
all((
string) $key));
195 public function remove($key)
197 $key = strtr($key, self::UPPER, self::LOWER);
199 unset($this->headers[$key]);
201 if (
'cache-control' === $key) {
202 $this->cacheControl = [];
215 public function getDate($key, \DateTime $default =
null)
217 if (
null === $value = $this->
get($key)) {
221 if (
false === $date = \DateTime::createFromFormat(DATE_RFC2822, $value)) {
222 throw new \RuntimeException(sprintf(
'The "%s" HTTP header is not parseable (%s).', $key, $value));
236 $this->cacheControl[$key] = $value;
250 return \array_key_exists($key, $this->cacheControl);
262 return \array_key_exists($key, $this->cacheControl) ? $this->cacheControl[$key] :
null;
272 unset($this->cacheControl[$key]);
284 return new \ArrayIterator($this->headers);
294 return \count($this->headers);
299 ksort($this->cacheControl);