class HeadersCacheContext in Drupal 9
Same name and namespace in other branches
- 8 core/lib/Drupal/Core/Cache/Context/HeadersCacheContext.php \Drupal\Core\Cache\Context\HeadersCacheContext
Defines the HeadersCacheContext service, for "per header" caching.
Cache context ID: 'headers' (to vary by all headers). Calculated cache context ID: 'headers:%name', e.g. 'headers:X-Something' (to vary by the 'X-Something' header).
Hierarchy
- class \Drupal\Core\Cache\Context\RequestStackCacheContextBase
- class \Drupal\Core\Cache\Context\HeadersCacheContext implements CalculatedCacheContextInterface
Expanded class hierarchy of HeadersCacheContext
1 file declares its use of HeadersCacheContext
- HeadersCacheContextTest.php in core/
tests/ Drupal/ Tests/ Core/ Cache/ Context/ HeadersCacheContextTest.php
1 string reference to 'HeadersCacheContext'
- core.services.yml in core/
core.services.yml - core/core.services.yml
1 service uses HeadersCacheContext
File
- core/
lib/ Drupal/ Core/ Cache/ Context/ HeadersCacheContext.php, line 14
Namespace
Drupal\Core\Cache\ContextView source
class HeadersCacheContext extends RequestStackCacheContextBase implements CalculatedCacheContextInterface {
/**
* {@inheritdoc}
*/
public static function getLabel() {
return t('HTTP headers');
}
/**
* {@inheritdoc}
*/
public function getContext($header = NULL) {
if ($header === NULL) {
$headers = $this->requestStack
->getCurrentRequest()->headers
->all();
// Order headers by name to have less cache variations.
ksort($headers);
$result = '';
foreach ($headers as $name => $value) {
if ($result) {
$result .= '&';
}
// Sort values to minimize cache variations.
sort($value);
$result .= $name . '=' . implode(',', $value);
}
return $result;
}
elseif ($this->requestStack
->getCurrentRequest()->headers
->has($header)) {
$value = $this->requestStack
->getCurrentRequest()->headers
->get($header);
if ($value !== '') {
return $value;
}
return '?valueless?';
}
return '';
}
/**
* {@inheritdoc}
*/
public function getCacheableMetadata($header = NULL) {
return new CacheableMetadata();
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
HeadersCacheContext:: |
public | function |
Gets the cacheability metadata for the context based on the parameter value. Overrides CalculatedCacheContextInterface:: |
|
HeadersCacheContext:: |
public | function |
Returns the string representation of the cache context. Overrides CalculatedCacheContextInterface:: |
|
HeadersCacheContext:: |
public static | function |
Returns the label of the cache context. Overrides CalculatedCacheContextInterface:: |
|
RequestStackCacheContextBase:: |
protected | property | The request stack. | |
RequestStackCacheContextBase:: |
public | function | Constructs a new RequestStackCacheContextBase class. |