You are here

public function OgRoleCacheContext::getContext in Organic groups 8

Returns the string representation of the cache context.

A cache context service's name is used as a token (placeholder) cache key, and is then replaced with the string returned by this method.

Return value

string The string representation of the cache context.

Overrides CacheContextInterface::getContext

File

src/Cache/Context/OgRoleCacheContext.php, line 112

Class

OgRoleCacheContext
Defines a cache context service for the OG roles of the current user.

Namespace

Drupal\og\Cache\Context

Code

public function getContext() {

  // Due to cacheability metadata bubbling this can be called often. Only
  // compute the hash once.
  if (empty($this->hashes[$this->user
    ->id()])) {

    // If the memberships are stored in a SQL database, use a fast SELECT
    // query to retrieve the membership data. If not, fall back to loading
    // the full membership entities.
    $storage = $this->entityTypeManager
      ->getStorage('og_membership');
    $memberships = $storage instanceof SqlContentEntityStorage ? $this
      ->getMembershipsFromDatabase() : $this
      ->getMembershipsFromEntities();

    // Sort the memberships, so that the same key can be generated, even if
    // the memberships were defined in a different order.
    ksort($memberships);
    foreach ($memberships as &$groups) {
      ksort($groups);
      foreach ($groups as &$role_names) {
        sort($role_names);
      }
    }

    // If the user is not a member of any groups, return a unique key.
    $this->hashes[$this->user
      ->id()] = empty($memberships) ? self::NO_CONTEXT : $this
      ->hash(serialize($memberships));
  }
  return $this->hashes[$this->user
    ->id()];
}