You are here

protected function OgRoleCacheContext::getMembershipsFromDatabase in Organic groups 8

Returns membership information by performing a database query.

This method retrieves the membership data by doing a direct SELECT query on the membership database. This is very fast but can only be done on SQL databases since the query requires a JOIN between two tables.

Return value

array[][] An array containing membership information for the current user. The data is in the format [$entity_type_id][$entity_id][$role_name].

1 call to OgRoleCacheContext::getMembershipsFromDatabase()
OgRoleCacheContext::getContext in src/Cache/Context/OgRoleCacheContext.php
Returns the string representation of the cache context.

File

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

Class

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

Namespace

Drupal\og\Cache\Context

Code

protected function getMembershipsFromDatabase() : array {
  $storage = $this->entityTypeManager
    ->getStorage('og_membership');
  if (!$storage instanceof SqlContentEntityStorage) {
    throw new \LogicException('Can only retrieve memberships directly from SQL databases.');
  }

  /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
  $table_mapping = $storage
    ->getTableMapping();
  $base_table = $table_mapping
    ->getBaseTable();
  $role_table = $table_mapping
    ->getFieldTableName('roles');
  $query = $this->database
    ->select($base_table, 'm');
  $query
    ->leftJoin($role_table, 'r', 'm.id = r.entity_id');
  $query
    ->fields('m', [
    'entity_type',
    'entity_bundle',
    'entity_id',
  ]);
  $query
    ->fields('r', [
    'roles_target_id',
  ]);
  $query
    ->condition('m.uid', $this->user
    ->id());
  $query
    ->condition('m.state', OgMembershipInterface::STATE_ACTIVE);
  $memberships = [];
  foreach ($query
    ->execute() as $row) {
    $entity_type_id = $row->entity_type;
    $entity_bundle_id = $row->entity_bundle;
    $entity_id = $row->entity_id;
    $role_name = $row->roles_target_id;

    // If the role name is empty this is a regular authenticated user. If it
    // is set we can derive the role name from the role ID.
    if (empty($role_name)) {
      $role_name = OgRoleInterface::AUTHENTICATED;
    }
    else {
      $pattern = preg_quote("{$entity_type_id}-{$entity_bundle_id}-");
      preg_match("/{$pattern}(.+)/", $row->roles_target_id, $matches);
      $role_name = $matches[1];
    }
    $memberships[$entity_type_id][$entity_id][] = $role_name;
  }
  return $memberships;
}