You are here

public function GroupPermissionsHashGenerator::generateHash in Group 8

Same name and namespace in other branches
  1. 2.0.x src/Access/GroupPermissionsHashGenerator.php \Drupal\group\Access\GroupPermissionsHashGenerator::generateHash()

Generates a hash for an account's complete group permissions.

Parameters

\Drupal\Core\Session\AccountInterface $account: The user account for which to get the permissions hash.

Return value

string A permissions hash.

Overrides GroupPermissionsHashGeneratorInterface::generateHash

File

src/Access/GroupPermissionsHashGenerator.php, line 57

Class

GroupPermissionsHashGenerator
Generates and caches the permissions hash for a group membership.

Namespace

Drupal\group\Access

Code

public function generateHash(AccountInterface $account) {

  // We can use a simple per-user static cache here because we already cache
  // the permissions more efficiently in the group permission calculator. On
  // top of that, there is only a tiny chance of a hash being generated for
  // more than one account during a single request.
  $cid = 'group_permissions_hash_' . $account
    ->id();

  // Retrieve the hash from the static cache if available.
  if ($static_cache = $this->static
    ->get($cid)) {
    return $static_cache->data;
  }
  else {
    $calculated_permissions = $this->groupPermissionCalculator
      ->calculatePermissions($account);
    $permissions = [];
    foreach ($calculated_permissions
      ->getItems() as $item) {

      // If the calculated permissions item grants admin rights, we can
      // simplify the entry by setting it to 'is-admin' rather than a list of
      // permissions. This will ensure admins for the given scope item always
      // match even if their list of permissions differs.
      if ($item
        ->isAdmin()) {
        $item_permissions = 'is-admin';
      }
      else {
        $item_permissions = $item
          ->getPermissions();

        // Sort the permissions by name to ensure we don't get mismatching
        // hashes for people with the same permissions, just because the order
        // of the permissions happened to differ.
        sort($item_permissions);
      }
      $permissions[$item
        ->getIdentifier()] = $item_permissions;
    }

    // Sort the result by key to ensure we don't get mismatching hashes for
    // people with the same permissions, just because the order of the keys
    // happened to differ.
    ksort($permissions);
    $hash = $this
      ->hash(serialize($permissions));
    $this->static
      ->set($cid, $hash, Cache::PERMANENT, $calculated_permissions
      ->getCacheTags());
    return $hash;
  }
}