function CacheContextsManager::convertTokensToKeys

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

Converts cache context tokens to cache keys.

A cache context token is either:

  • a cache context ID (if the service ID is 'cache_context.foo', then 'foo' is a cache context ID); for example, 'foo'.
  • a calculated cache context ID, followed by a colon, followed by the parameter for the calculated cache context; for example, 'bar:some_parameter'.

Parameters

string[] $context_tokens: An array of cache context tokens.

Return value

\Drupal\Core\Cache\Context\ContextCacheKeys The ContextCacheKeys object containing the converted cache keys and cacheability metadata.

File

core/lib/Drupal/Core/Cache/Context/CacheContextsManager.php, line 107

Class

CacheContextsManager
Converts cache context tokens into cache keys.

Namespace

Drupal\Core\Cache\Context

Code

public function convertTokensToKeys(array $context_tokens) {
    assert($this->assertValidTokens($context_tokens));
    $cacheable_metadata = new CacheableMetadata();
    $optimized_tokens = $this->optimizeTokens($context_tokens);
    // Iterate over cache contexts that have been optimized away and get their
    // cacheability metadata.
    foreach (static::parseTokens(array_diff($context_tokens, $optimized_tokens)) as $context_token) {
        [
            $context_id,
            $parameter,
        ] = $context_token;
        $context = $this->getService($context_id);
        $cacheable_metadata = $cacheable_metadata->merge($context->getCacheableMetadata($parameter));
    }
    sort($optimized_tokens);
    $keys = [];
    foreach (array_combine($optimized_tokens, static::parseTokens($optimized_tokens)) as $context_token => $context) {
        [
            $context_id,
            $parameter,
        ] = $context;
        $keys[] = '[' . $context_token . ']=' . $this->getService($context_id)
            ->getContext($parameter);
    }
    // Create the returned object and merge in the cacheability metadata.
    $context_cache_keys = new ContextCacheKeys($keys);
    return $context_cache_keys->merge($cacheable_metadata);
}

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