You are here

public function MembershipManager::getGroupContentIds in Organic groups 8

Returns all the group content IDs associated with a given group entity.

This does not return information about users that are members of the given group.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The group entity for which to return group content IDs.

array $entity_types: Optional list of group content entity types for which to return results. If an empty array is passed, the group content is not filtered. Defaults to an empty array.

Return value

array An associative array, keyed by group content entity type, each item an array of group content entity IDs.

Overrides MembershipManagerInterface::getGroupContentIds

File

src/MembershipManager.php, line 367

Class

MembershipManager
Service for managing memberships and group content.

Namespace

Drupal\og

Code

public function getGroupContentIds(EntityInterface $entity, array $entity_types = []) {
  $group_content = [];

  // Retrieve the fields which reference our entity type and bundle.
  $query = $this->entityTypeManager
    ->getStorage('field_storage_config')
    ->getQuery()
    ->condition('type', OgGroupAudienceHelperInterface::GROUP_REFERENCE);

  // Optionally filter group content entity types.
  if ($entity_types) {
    $query
      ->condition('entity_type', $entity_types, 'IN');
  }

  /** @var \Drupal\field\FieldStorageConfigInterface[] $fields */
  $storage = $this->entityTypeManager
    ->getStorage('field_storage_config');
  $fields = array_filter($storage
    ->loadMultiple($query
    ->execute()), function (FieldStorageConfigInterface $field) use ($entity) {
    $type_matches = $field
      ->getSetting('target_type') === $entity
      ->getEntityTypeId();

    // If the list of target bundles is empty, it targets all bundles.
    $bundle_matches = empty($field
      ->getSetting('target_bundles')) || in_array($entity
      ->bundle(), $field
      ->getSetting('target_bundles'));
    return $type_matches && $bundle_matches;
  });

  // Compile the group content.
  foreach ($fields as $field) {
    $group_content_entity_type = $field
      ->getTargetEntityTypeId();

    // Group the group content per entity type.
    if (!isset($group_content[$group_content_entity_type])) {
      $group_content[$group_content_entity_type] = [];
    }

    // Query all group content that references the group through this field.
    $results = $this->entityTypeManager
      ->getStorage($group_content_entity_type)
      ->getQuery()
      ->condition($field
      ->getName() . '.target_id', $entity
      ->id())
      ->execute();
    $group_content[$group_content_entity_type] = array_merge($group_content[$group_content_entity_type], $results);
  }
  return $group_content;
}