Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. HeaderBag.php

class HeaderBag

HeaderBag is a container for HTTP headers.

@author Fabien Potencier <fabien@symfony.com>

@implements \IteratorAggregate<string, list<string|null>>

Hierarchy

  • class \Symfony\Component\HttpFoundation\HeaderBag implements \Symfony\Component\HttpFoundation\IteratorAggregate, \Symfony\Component\HttpFoundation\Countable, \Symfony\Component\HttpFoundation\Stringable

Expanded class hierarchy of HeaderBag

File

vendor/symfony/http-foundation/HeaderBag.php, line 21

Namespace

Symfony\Component\HttpFoundation
View source
class HeaderBag implements \IteratorAggregate, \Countable, \Stringable {
    protected const UPPER = '_ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    protected const LOWER = '-abcdefghijklmnopqrstuvwxyz';
    
    /**
     * @var array<string, list<string|null>>
     */
    protected array $headers = [];
    protected array $cacheControl = [];
    public function __construct(array $headers = []) {
        foreach ($headers as $key => $values) {
            $this->set($key, $values);
        }
    }
    
    /**
     * Returns the headers as a string.
     */
    public function __toString() : string {
        if (!($headers = $this->all())) {
            return '';
        }
        ksort($headers);
        $max = max(array_map('strlen', array_keys($headers))) + 1;
        $content = '';
        foreach ($headers as $name => $values) {
            $name = ucwords($name, '-');
            foreach ($values as $value) {
                $content .= \sprintf("%-{$max}s %s\r\n", $name . ':', $value);
            }
        }
        return $content;
    }
    
    /**
     * Returns the headers.
     *
     * @param string|null $key The name of the headers to return or null to get them all
     *
     * @return ($key is null ? array<string, list<string|null>> : list<string|null>)
     */
    public function all(?string $key = null) : array {
        if (null !== $key) {
            return $this->headers[strtr($key, self::UPPER, self::LOWER)] ?? [];
        }
        return $this->headers;
    }
    
    /**
     * Returns the parameter keys.
     *
     * @return string[]
     */
    public function keys() : array {
        return array_keys($this->all());
    }
    
    /**
     * Replaces the current HTTP headers by a new set.
     */
    public function replace(array $headers = []) : void {
        $this->headers = [];
        $this->add($headers);
    }
    
    /**
     * Adds new headers the current HTTP headers set.
     */
    public function add(array $headers) : void {
        foreach ($headers as $key => $values) {
            $this->set($key, $values);
        }
    }
    
    /**
     * Returns the first header by name or the default one.
     */
    public function get(string $key, ?string $default = null) : ?string {
        $headers = $this->all($key);
        if (!$headers) {
            return $default;
        }
        if (null === $headers[0]) {
            return null;
        }
        return $headers[0];
    }
    
    /**
     * Sets a header by name.
     *
     * @param string|string[]|null $values  The value or an array of values
     * @param bool                 $replace Whether to replace the actual value or not (true by default)
     */
    public function set(string $key, string|array|null $values, bool $replace = true) : void {
        $key = strtr($key, self::UPPER, self::LOWER);
        if (\is_array($values)) {
            $values = array_values($values);
            if (true === $replace || !isset($this->headers[$key])) {
                $this->headers[$key] = $values;
            }
            else {
                $this->headers[$key] = array_merge($this->headers[$key], $values);
            }
        }
        else {
            if (true === $replace || !isset($this->headers[$key])) {
                $this->headers[$key] = [
                    $values,
                ];
            }
            else {
                $this->headers[$key][] = $values;
            }
        }
        if ('cache-control' === $key) {
            $this->cacheControl = $this->parseCacheControl(implode(', ', $this->headers[$key]));
        }
    }
    
    /**
     * Returns true if the HTTP header is defined.
     */
    public function has(string $key) : bool {
        return \array_key_exists(strtr($key, self::UPPER, self::LOWER), $this->all());
    }
    
    /**
     * Returns true if the given HTTP header contains the given value.
     */
    public function contains(string $key, string $value) : bool {
        return \in_array($value, $this->all($key), true);
    }
    
    /**
     * Removes a header.
     */
    public function remove(string $key) : void {
        $key = strtr($key, self::UPPER, self::LOWER);
        unset($this->headers[$key]);
        if ('cache-control' === $key) {
            $this->cacheControl = [];
        }
    }
    
    /**
     * Returns the HTTP header value converted to a date.
     *
     * @throws \RuntimeException When the HTTP header is not parseable
     */
    public function getDate(string $key, ?\DateTimeInterface $default = null) : ?\DateTimeImmutable {
        if (null === ($value = $this->get($key))) {
            return null !== $default ? \DateTimeImmutable::createFromInterface($default) : null;
        }
        if (false === ($date = \DateTimeImmutable::createFromFormat(\DATE_RFC2822, $value))) {
            throw new \RuntimeException(\sprintf('The "%s" HTTP header is not parseable (%s).', $key, $value));
        }
        return $date;
    }
    
    /**
     * Adds a custom Cache-Control directive.
     */
    public function addCacheControlDirective(string $key, bool|string $value = true) : void {
        $this->cacheControl[$key] = $value;
        $this->set('Cache-Control', $this->getCacheControlHeader());
    }
    
    /**
     * Returns true if the Cache-Control directive is defined.
     */
    public function hasCacheControlDirective(string $key) : bool {
        return \array_key_exists($key, $this->cacheControl);
    }
    
    /**
     * Returns a Cache-Control directive value by name.
     */
    public function getCacheControlDirective(string $key) : bool|string|null {
        return $this->cacheControl[$key] ?? null;
    }
    
    /**
     * Removes a Cache-Control directive.
     */
    public function removeCacheControlDirective(string $key) : void {
        unset($this->cacheControl[$key]);
        $this->set('Cache-Control', $this->getCacheControlHeader());
    }
    
    /**
     * Returns an iterator for headers.
     *
     * @return \ArrayIterator<string, list<string|null>>
     */
    public function getIterator() : \ArrayIterator {
        return new \ArrayIterator($this->headers);
    }
    
    /**
     * Returns the number of headers.
     */
    public function count() : int {
        return \count($this->headers);
    }
    protected function getCacheControlHeader() : string {
        ksort($this->cacheControl);
        return HeaderUtils::toString($this->cacheControl, ',');
    }
    
    /**
     * Parses a Cache-Control HTTP header.
     */
    protected function parseCacheControl(string $header) : array {
        $parts = HeaderUtils::split($header, ',=');
        return HeaderUtils::combine($parts);
    }

}

Members

Title Sort descending Modifiers Object type Summary Overrides
HeaderBag::$cacheControl protected property
HeaderBag::$headers protected property
HeaderBag::add public function Adds new headers the current HTTP headers set.
HeaderBag::addCacheControlDirective public function Adds a custom Cache-Control directive.
HeaderBag::all public function Returns the headers. 1
HeaderBag::contains public function Returns true if the given HTTP header contains the given value.
HeaderBag::count public function Returns the number of headers.
HeaderBag::get public function Returns the first header by name or the default one.
HeaderBag::getCacheControlDirective public function Returns a Cache-Control directive value by name. 1
HeaderBag::getCacheControlHeader protected function
HeaderBag::getDate public function Returns the HTTP header value converted to a date.
HeaderBag::getIterator public function Returns an iterator for headers.
HeaderBag::has public function Returns true if the HTTP header is defined.
HeaderBag::hasCacheControlDirective public function Returns true if the Cache-Control directive is defined. 1
HeaderBag::keys public function Returns the parameter keys.
HeaderBag::LOWER protected constant
HeaderBag::parseCacheControl protected function Parses a Cache-Control HTTP header.
HeaderBag::remove public function Removes a header. 1
HeaderBag::removeCacheControlDirective public function Removes a Cache-Control directive.
HeaderBag::replace public function Replaces the current HTTP headers by a new set. 1
HeaderBag::set public function Sets a header by name. 1
HeaderBag::UPPER protected constant
HeaderBag::__construct public function 1
HeaderBag::__toString public function Returns the headers as a string.

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal