You are here

public function AccountPermissionsCacheContext::getCacheableMetadata in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Cache/Context/AccountPermissionsCacheContext.php \Drupal\Core\Cache\Context\AccountPermissionsCacheContext::getCacheableMetadata()
  2. 10 core/lib/Drupal/Core/Cache/Context/AccountPermissionsCacheContext.php \Drupal\Core\Cache\Context\AccountPermissionsCacheContext::getCacheableMetadata()

Gets the cacheability metadata for the context.

There are three valid cases for the returned CacheableMetadata object:

  • An empty object means this can be optimized away safely.
  • A max-age of 0 means that this context can never be optimized away. It will never bubble up and cache tags will not be used.
  • Any non-zero max-age and cache tags will bubble up into the cache item if this is optimized away to allow for invalidation if the context value changes.

Return value

\Drupal\Core\Cache\CacheableMetadata A cacheable metadata object.

Overrides CacheContextInterface::getCacheableMetadata

File

core/lib/Drupal/Core/Cache/Context/AccountPermissionsCacheContext.php, line 53

Class

AccountPermissionsCacheContext
Defines the AccountPermissionsCacheContext service, for "per permission" caching.

Namespace

Drupal\Core\Cache\Context

Code

public function getCacheableMetadata() {
  $cacheable_metadata = new CacheableMetadata();

  // The permissions hash changes when:
  // - a user is updated to have different roles;
  $tags = [
    'user:' . $this->user
      ->id(),
  ];

  // - a role is updated to have different permissions.
  foreach ($this->user
    ->getRoles() as $rid) {
    $tags[] = "config:user.role.{$rid}";
  }
  return $cacheable_metadata
    ->setCacheTags($tags);
}