function CacheContextsManager::validateTokens

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

Validates an array of cache context tokens.

Can be called before using cache contexts in operations, to check validity.

Parameters

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

Throws

\LogicException

See also

\Drupal\Core\Cache\Context\CacheContextsManager::parseTokens()

1 call to CacheContextsManager::validateTokens()
CacheContextsManager::assertValidTokens in core/lib/Drupal/Core/Cache/Context/CacheContextsManager.php
Asserts the context tokens are valid.

File

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

Class

CacheContextsManager
Converts cache context tokens into cache keys.

Namespace

Drupal\Core\Cache\Context

Code

public function validateTokens(array $context_tokens = []) {
    if (empty($context_tokens)) {
        return;
    }
    // Initialize the set of valid context tokens with the container's contexts.
    if (!isset($this->validContextTokens)) {
        $this->validContextTokens = array_flip($this->contexts);
    }
    foreach ($context_tokens as $context_token) {
        if (!is_string($context_token)) {
            throw new \LogicException(sprintf('Cache contexts must be strings, %s given.', gettype($context_token)));
        }
        if (isset($this->validContextTokens[$context_token])) {
            continue;
        }
        // If it's a valid context token, then the ID must be stored in the set
        // of valid context tokens (since we initialized it with the list of cache
        // context IDs using the container). In case of an invalid context token,
        // throw an exception, otherwise cache it, including the parameter, to
        // minimize the amount of work in future ::validateContexts() calls.
        $context_id = $context_token;
        $colon_pos = strpos($context_id, ':');
        if ($colon_pos !== FALSE) {
            $context_id = substr($context_id, 0, $colon_pos);
        }
        if (isset($this->validContextTokens[$context_id])) {
            $this->validContextTokens[$context_token] = TRUE;
        }
        else {
            throw new \LogicException(sprintf('"%s" is not a valid cache context ID.', $context_id));
        }
    }
}

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