This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Component/HttpFoundation/HeaderBag.php

309 lines
8.0 KiB
PHP
Raw Normal View History

<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpFoundation;
/**
2010-06-23 15:24:24 +01:00
* HeaderBag is a container for HTTP headers.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class HeaderBag implements \IteratorAggregate, \Countable
{
2019-01-16 18:24:45 +00:00
protected $headers = [];
protected $cacheControl = [];
2019-01-16 18:24:45 +00:00
public function __construct(array $headers = [])
{
foreach ($headers as $key => $values) {
$this->set($key, $values);
}
}
/**
* Returns the headers as a string.
*
* @return string The headers
*/
public function __toString()
{
if (!$headers = $this->all()) {
2011-05-15 18:44:22 +01:00
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;
}
2010-06-23 15:24:24 +01:00
/**
* Returns the headers.
*
* @param string|null $key The name of the headers to return or null to get them all
*
2010-06-23 15:24:24 +01:00
* @return array An array of headers
*/
public function all(/*string $key = null*/)
2010-06-23 15:24:24 +01:00
{
if (1 <= \func_num_args() && null !== $key = func_get_arg(0)) {
$key = str_replace('_', '-', strtolower($key));
return $this->headers[$key] ?? [];
}
2010-06-23 15:24:24 +01:00
return $this->headers;
}
/**
* Returns the parameter keys.
*
* @return array An array of parameter keys
*/
public function keys()
{
return array_keys($this->all());
}
/**
* Replaces the current HTTP headers by a new set.
*/
2019-01-16 18:24:45 +00:00
public function replace(array $headers = [])
{
2019-01-16 18:24:45 +00:00
$this->headers = [];
$this->add($headers);
}
/**
* Adds new headers the current HTTP headers set.
*/
public function add(array $headers)
{
2010-06-23 15:24:24 +01:00
foreach ($headers as $key => $values) {
$this->set($key, $values);
}
}
/**
* Returns a header value by name.
*
* @param string $key The header name
* @param string|null $default The default value
2010-06-23 15:24:24 +01:00
*
* @return string|null The first header value or default value
*/
public function get($key, $default = null)
{
$headers = $this->all((string) $key);
if (2 < \func_num_args()) {
@trigger_error(sprintf('Passing a third argument to "%s()" is deprecated since Symfony 4.4, use method "all()" instead', __METHOD__), E_USER_DEPRECATED);
if (!func_get_arg(2)) {
return $headers;
}
2010-06-23 15:24:24 +01:00
}
2011-02-27 17:28:11 +00:00
return isset($headers[0]) ? (string) $headers[0] : $default;
}
/**
* Sets a header by name.
*
* @param string $key The key
* @param string|string[] $values The value or an array of values
* @param bool $replace Whether to replace the actual value or not (true by default)
*/
2010-06-23 15:24:24 +01:00
public function set($key, $values, $replace = true)
{
$key = str_replace('_', '-', strtolower($key));
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);
}
2010-06-23 15:24:24 +01:00
} else {
if (true === $replace || !isset($this->headers[$key])) {
2019-01-16 18:24:45 +00:00
$this->headers[$key] = [$values];
} else {
$this->headers[$key][] = $values;
}
2010-06-23 15:24:24 +01:00
}
if ('cache-control' === $key) {
$this->cacheControl = $this->parseCacheControl(implode(', ', $this->headers[$key]));
}
}
/**
* Returns true if the HTTP header is defined.
*
* @param string $key The HTTP header
*
2014-11-30 13:33:44 +00:00
* @return bool true if the parameter exists, false otherwise
*/
public function has($key)
2010-05-03 17:10:24 +01:00
{
return \array_key_exists(str_replace('_', '-', strtolower($key)), $this->all());
2010-05-03 17:10:24 +01:00
}
[HttpKernel] removed Response assertions They are too magic and they don't really add value: $this->assertResponseStatusCodeEmpty($client); $this->assertTrue($client->getResponse()->isEmpty()); $this->assertResponseStatusCodeNotFound($client); $this->assertTrue($client->getResponse()->isNotFound()); $this->assertResponseStatusCodeForbidden($client); $this->assertTrue($client->getResponse()->isForbidden()); $this->assertResponseStatusCodeOk($client); $this->assertTrue($client->getResponse()->isOk()); $this->assertResponseStatusCodeServerError($client); $this->assertTrue($client->getResponse()->isServerError()); $this->assertResponseStatusCodeClientError($client); $this->assertTrue($client->getResponse()->isClientError()); $this->assertResponseStatusCodeRedirection($client); $this->assertTrue($client->getResponse()->isRedirection()); $this->assertResponseStatusCodeSuccessful($client); $this->assertTrue($client->getResponse()->isSuccessful()); $this->assertResponseStatusCodeInformational($client); $this->assertTrue($client->getResponse()->isInformational()); $this->assertResponseStatusCode(200, $client); $this->assertEquals(200, $client->getResponse()->getStatusCode()); $this->assertResponseStatusCodeRedirect('google.com', $client); $this->assertTrue($client->getResponse()->isRedirected('google.com')); $this->assertResponseNotRegExp('/foo/', $client); $this->assertNotRegExp('/foo', $client->getResponse()->getContent()); $this->assertResponseRegExp('/foo/', $client); $this->assertRegExp('/foo', $client->getResponse()->getContent()); $this->assertResponseNotSelectExists('h1', $client); $this->assertTrue($crawler->filter('h1')->isEmpty()); $this->assertResponseSelectExists('h1', $client); $this->assertFalse($crawler->filter('h1')->isEmpty()); $this->assertResponseSelectCount(3, 'h1', $client); $this->assertEquals(3, $crawler->filter('h1')->count()); $this->assertResponseSelectEquals($expected, $selector, $arguments, $client); $this->assertEquals($expected, $crawler->filter($selector)->extract($arguments)); $this->assertResponseHeaderEquals($value, $key, $client); $this->assertTrue($client->getResponse()->headers->contains($key, $value)); $this->assertResponseNotHeaderEquals($value, $key, $client); $this->assertFalse($client->getResponse()->headers->contains($key, $value)); $this->assertResponseHeaderRegExp($regex, $key, $client); $this->assertRegExp($regex, $client->getResponse()->headers->get($key)); $this->assertResponseNotHeaderRegExp($regex, $key, $client); $this->assertNotRegExp($regex, $client->getResponse()->headers->get($key)); $this->assertResponseCookie($value, $attributes, $name, $client); $this->assertTrue($client->getResponse()->hasCookie($name));
2010-06-23 09:39:33 +01:00
/**
* Returns true if the given HTTP header contains the given value.
*
* @param string $key The HTTP header name
* @param string $value The HTTP value
*
2014-11-30 13:33:44 +00:00
* @return bool true if the value is contained in the header, false otherwise
[HttpKernel] removed Response assertions They are too magic and they don't really add value: $this->assertResponseStatusCodeEmpty($client); $this->assertTrue($client->getResponse()->isEmpty()); $this->assertResponseStatusCodeNotFound($client); $this->assertTrue($client->getResponse()->isNotFound()); $this->assertResponseStatusCodeForbidden($client); $this->assertTrue($client->getResponse()->isForbidden()); $this->assertResponseStatusCodeOk($client); $this->assertTrue($client->getResponse()->isOk()); $this->assertResponseStatusCodeServerError($client); $this->assertTrue($client->getResponse()->isServerError()); $this->assertResponseStatusCodeClientError($client); $this->assertTrue($client->getResponse()->isClientError()); $this->assertResponseStatusCodeRedirection($client); $this->assertTrue($client->getResponse()->isRedirection()); $this->assertResponseStatusCodeSuccessful($client); $this->assertTrue($client->getResponse()->isSuccessful()); $this->assertResponseStatusCodeInformational($client); $this->assertTrue($client->getResponse()->isInformational()); $this->assertResponseStatusCode(200, $client); $this->assertEquals(200, $client->getResponse()->getStatusCode()); $this->assertResponseStatusCodeRedirect('google.com', $client); $this->assertTrue($client->getResponse()->isRedirected('google.com')); $this->assertResponseNotRegExp('/foo/', $client); $this->assertNotRegExp('/foo', $client->getResponse()->getContent()); $this->assertResponseRegExp('/foo/', $client); $this->assertRegExp('/foo', $client->getResponse()->getContent()); $this->assertResponseNotSelectExists('h1', $client); $this->assertTrue($crawler->filter('h1')->isEmpty()); $this->assertResponseSelectExists('h1', $client); $this->assertFalse($crawler->filter('h1')->isEmpty()); $this->assertResponseSelectCount(3, 'h1', $client); $this->assertEquals(3, $crawler->filter('h1')->count()); $this->assertResponseSelectEquals($expected, $selector, $arguments, $client); $this->assertEquals($expected, $crawler->filter($selector)->extract($arguments)); $this->assertResponseHeaderEquals($value, $key, $client); $this->assertTrue($client->getResponse()->headers->contains($key, $value)); $this->assertResponseNotHeaderEquals($value, $key, $client); $this->assertFalse($client->getResponse()->headers->contains($key, $value)); $this->assertResponseHeaderRegExp($regex, $key, $client); $this->assertRegExp($regex, $client->getResponse()->headers->get($key)); $this->assertResponseNotHeaderRegExp($regex, $key, $client); $this->assertNotRegExp($regex, $client->getResponse()->headers->get($key)); $this->assertResponseCookie($value, $attributes, $name, $client); $this->assertTrue($client->getResponse()->hasCookie($name));
2010-06-23 09:39:33 +01:00
*/
public function contains($key, $value)
{
return \in_array($value, $this->all((string) $key));
[HttpKernel] removed Response assertions They are too magic and they don't really add value: $this->assertResponseStatusCodeEmpty($client); $this->assertTrue($client->getResponse()->isEmpty()); $this->assertResponseStatusCodeNotFound($client); $this->assertTrue($client->getResponse()->isNotFound()); $this->assertResponseStatusCodeForbidden($client); $this->assertTrue($client->getResponse()->isForbidden()); $this->assertResponseStatusCodeOk($client); $this->assertTrue($client->getResponse()->isOk()); $this->assertResponseStatusCodeServerError($client); $this->assertTrue($client->getResponse()->isServerError()); $this->assertResponseStatusCodeClientError($client); $this->assertTrue($client->getResponse()->isClientError()); $this->assertResponseStatusCodeRedirection($client); $this->assertTrue($client->getResponse()->isRedirection()); $this->assertResponseStatusCodeSuccessful($client); $this->assertTrue($client->getResponse()->isSuccessful()); $this->assertResponseStatusCodeInformational($client); $this->assertTrue($client->getResponse()->isInformational()); $this->assertResponseStatusCode(200, $client); $this->assertEquals(200, $client->getResponse()->getStatusCode()); $this->assertResponseStatusCodeRedirect('google.com', $client); $this->assertTrue($client->getResponse()->isRedirected('google.com')); $this->assertResponseNotRegExp('/foo/', $client); $this->assertNotRegExp('/foo', $client->getResponse()->getContent()); $this->assertResponseRegExp('/foo/', $client); $this->assertRegExp('/foo', $client->getResponse()->getContent()); $this->assertResponseNotSelectExists('h1', $client); $this->assertTrue($crawler->filter('h1')->isEmpty()); $this->assertResponseSelectExists('h1', $client); $this->assertFalse($crawler->filter('h1')->isEmpty()); $this->assertResponseSelectCount(3, 'h1', $client); $this->assertEquals(3, $crawler->filter('h1')->count()); $this->assertResponseSelectEquals($expected, $selector, $arguments, $client); $this->assertEquals($expected, $crawler->filter($selector)->extract($arguments)); $this->assertResponseHeaderEquals($value, $key, $client); $this->assertTrue($client->getResponse()->headers->contains($key, $value)); $this->assertResponseNotHeaderEquals($value, $key, $client); $this->assertFalse($client->getResponse()->headers->contains($key, $value)); $this->assertResponseHeaderRegExp($regex, $key, $client); $this->assertRegExp($regex, $client->getResponse()->headers->get($key)); $this->assertResponseNotHeaderRegExp($regex, $key, $client); $this->assertNotRegExp($regex, $client->getResponse()->headers->get($key)); $this->assertResponseCookie($value, $attributes, $name, $client); $this->assertTrue($client->getResponse()->hasCookie($name));
2010-06-23 09:39:33 +01:00
}
/**
made some method name changes to have a better coherence throughout the framework When an object has a "main" many relation with related "things" (objects, parameters, ...), the method names are normalized: * get() * set() * all() * replace() * remove() * clear() * isEmpty() * add() * register() * count() * keys() The classes below follow this method naming convention: * BrowserKit\CookieJar -> Cookie * BrowserKit\History -> Request * Console\Application -> Command * Console\Application\Helper\HelperSet -> HelperInterface * DependencyInjection\Container -> services * DependencyInjection\ContainerBuilder -> services * DependencyInjection\ParameterBag\ParameterBag -> parameters * DependencyInjection\ParameterBag\FrozenParameterBag -> parameters * DomCrawler\Form -> FormField * EventDispatcher\Event -> parameters * Form\FieldGroup -> Field * HttpFoundation\HeaderBag -> headers * HttpFoundation\ParameterBag -> parameters * HttpFoundation\Session -> attributes * HttpKernel\Profiler\Profiler -> DataCollectorInterface * Routing\RouteCollection -> Route * Security\Authentication\AuthenticationProviderManager -> AuthenticationProviderInterface * Templating\Engine -> HelperInterface * Translation\MessageCatalogue -> messages The usage of these methods are only allowed when it is clear that there is a main relation: * a CookieJar has many Cookies; * a Container has many services and many parameters (as services is the main relation, we use the naming convention for this relation); * a Console Input has many arguments and many options. There is no "main" relation, and so the naming convention does not apply. For many relations where the convention does not apply, the following methods must be used instead (where XXX is the name of the related thing): * get() -> getXXX() * set() -> setXXX() * all() -> getXXXs() * replace() -> setXXXs() * remove() -> removeXXX() * clear() -> clearXXX() * isEmpty() -> isEmptyXXX() * add() -> addXXX() * register() -> registerXXX() * count() -> countXXX() * keys()
2010-11-23 08:42:19 +00:00
* Removes a header.
*
* @param string $key The HTTP header name
*/
made some method name changes to have a better coherence throughout the framework When an object has a "main" many relation with related "things" (objects, parameters, ...), the method names are normalized: * get() * set() * all() * replace() * remove() * clear() * isEmpty() * add() * register() * count() * keys() The classes below follow this method naming convention: * BrowserKit\CookieJar -> Cookie * BrowserKit\History -> Request * Console\Application -> Command * Console\Application\Helper\HelperSet -> HelperInterface * DependencyInjection\Container -> services * DependencyInjection\ContainerBuilder -> services * DependencyInjection\ParameterBag\ParameterBag -> parameters * DependencyInjection\ParameterBag\FrozenParameterBag -> parameters * DomCrawler\Form -> FormField * EventDispatcher\Event -> parameters * Form\FieldGroup -> Field * HttpFoundation\HeaderBag -> headers * HttpFoundation\ParameterBag -> parameters * HttpFoundation\Session -> attributes * HttpKernel\Profiler\Profiler -> DataCollectorInterface * Routing\RouteCollection -> Route * Security\Authentication\AuthenticationProviderManager -> AuthenticationProviderInterface * Templating\Engine -> HelperInterface * Translation\MessageCatalogue -> messages The usage of these methods are only allowed when it is clear that there is a main relation: * a CookieJar has many Cookies; * a Container has many services and many parameters (as services is the main relation, we use the naming convention for this relation); * a Console Input has many arguments and many options. There is no "main" relation, and so the naming convention does not apply. For many relations where the convention does not apply, the following methods must be used instead (where XXX is the name of the related thing): * get() -> getXXX() * set() -> setXXX() * all() -> getXXXs() * replace() -> setXXXs() * remove() -> removeXXX() * clear() -> clearXXX() * isEmpty() -> isEmptyXXX() * add() -> addXXX() * register() -> registerXXX() * count() -> countXXX() * keys()
2010-11-23 08:42:19 +00:00
public function remove($key)
{
$key = str_replace('_', '-', strtolower($key));
unset($this->headers[$key]);
if ('cache-control' === $key) {
2019-01-16 18:24:45 +00:00
$this->cacheControl = [];
}
}
/**
* Returns the HTTP header value converted to a date.
*
2019-08-11 10:15:18 +01:00
* @param string $key The parameter key
*
2019-08-11 10:15:18 +01:00
* @return \DateTimeInterface|null The parsed DateTime or the default value if the header does not exist
*
* @throws \RuntimeException When the HTTP header is not parseable
*/
public function getDate($key, \DateTime $default = null)
{
if (null === $value = $this->get($key)) {
return $default;
}
if (false === $date = \DateTime::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.
*
* @param string $key The Cache-Control directive name
* @param mixed $value The Cache-Control directive value
*/
public function addCacheControlDirective($key, $value = true)
{
$this->cacheControl[$key] = $value;
$this->set('Cache-Control', $this->getCacheControlHeader());
}
/**
* Returns true if the Cache-Control directive is defined.
*
* @param string $key The Cache-Control directive
*
* @return bool true if the directive exists, false otherwise
*/
public function hasCacheControlDirective($key)
{
return \array_key_exists($key, $this->cacheControl);
}
/**
* Returns a Cache-Control directive value by name.
*
* @param string $key The directive name
*
* @return mixed|null The directive value if defined, null otherwise
*/
public function getCacheControlDirective($key)
{
return \array_key_exists($key, $this->cacheControl) ? $this->cacheControl[$key] : null;
}
/**
* Removes a Cache-Control directive.
*
* @param string $key The Cache-Control directive
*/
public function removeCacheControlDirective($key)
{
unset($this->cacheControl[$key]);
$this->set('Cache-Control', $this->getCacheControlHeader());
}
/**
2012-03-23 12:49:00 +00:00
* Returns an iterator for headers.
*
2012-03-23 12:49:00 +00:00
* @return \ArrayIterator An \ArrayIterator instance
*/
public function getIterator()
{
return new \ArrayIterator($this->headers);
}
/**
2012-03-23 12:49:00 +00:00
* Returns the number of headers.
*
2012-03-23 12:49:00 +00:00
* @return int The number of headers
*/
public function count()
{
return \count($this->headers);
}
protected function getCacheControlHeader()
{
ksort($this->cacheControl);
return HeaderUtils::toString($this->cacheControl, ',');
}
/**
* Parses a Cache-Control HTTP header.
*
* @param string $header The value of the Cache-Control HTTP header
*
* @return array An array representing the attribute values
*/
protected function parseCacheControl($header)
{
$parts = HeaderUtils::split($header, ',=');
return HeaderUtils::combine($parts);
}
}