You are here

public function GroupMembershipLoader::loadByUser in Group 8

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

Loads all memberships for a user.

Parameters

\Drupal\Core\Session\AccountInterface $account: (optional) The user to load the membership for. Leave blank to load the memberships of the currently logged in user.

string|array $roles: (optional) A group role machine name or a list of group role machine names to filter on. Valid results only need to match on one role.

Return value

\Drupal\group\GroupMembership[] The loaded GroupMemberships matching the criteria.

Overrides GroupMembershipLoaderInterface::loadByUser

File

src/GroupMembershipLoader.php, line 104

Class

GroupMembershipLoader
Loader for wrapped GroupContent entities using the 'group_membership' plugin.

Namespace

Drupal\group

Code

public function loadByUser(AccountInterface $account = NULL, $roles = NULL) {
  if (!isset($account)) {
    $account = $this->currentUser;
  }

  // Load all group content types for the membership content enabler plugin.
  $group_content_types = $this->entityTypeManager
    ->getStorage('group_content_type')
    ->loadByProperties([
    'content_plugin' => 'group_membership',
  ]);

  // If none were found, there can be no memberships either.
  if (empty($group_content_types)) {
    return [];
  }

  // Try to load all possible membership group content for the user.
  $group_content_type_ids = [];
  foreach ($group_content_types as $group_content_type) {
    $group_content_type_ids[] = $group_content_type
      ->id();
  }
  $properties = [
    'type' => $group_content_type_ids,
    'entity_id' => $account
      ->id(),
  ];
  if (isset($roles)) {
    $properties['group_roles'] = (array) $roles;
  }

  /** @var \Drupal\group\Entity\GroupContentInterface[] $group_contents */
  $group_contents = $this
    ->groupContentStorage()
    ->loadByProperties($properties);
  return $this
    ->wrapGroupContentEntities($group_contents);
}