function HeadersCacheContext::getContext

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Cache/Context/HeadersCacheContext.php \Drupal\Core\Cache\Context\HeadersCacheContext::getContext()
  2. 8.9.x core/lib/Drupal/Core/Cache/Context/HeadersCacheContext.php \Drupal\Core\Cache\Context\HeadersCacheContext::getContext()
  3. 10 core/lib/Drupal/Core/Cache/Context/HeadersCacheContext.php \Drupal\Core\Cache\Context\HeadersCacheContext::getContext()

Overrides CalculatedCacheContextInterface::getContext

File

core/lib/Drupal/Core/Cache/Context/HeadersCacheContext.php, line 26

Class

HeadersCacheContext
Defines the HeadersCacheContext service, for "per header" caching.

Namespace

Drupal\Core\Cache\Context

Code

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 '';
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.