You are here

public function GroupContentStorage::loadByEntity in Group 8

Same name and namespace in other branches
  1. 2.0.x src/Entity/Storage/GroupContentStorage.php \Drupal\group\Entity\Storage\GroupContentStorage::loadByEntity()

Retrieves all GroupContent entities that represent a given entity.

Parameters

\Drupal\Core\Entity\ContentEntityInterface $entity: An entity which may be within one or more groups.

Return value

\Drupal\group\Entity\GroupContentInterface[] A list of GroupContent entities which refer to the given entity.

Overrides GroupContentStorageInterface::loadByEntity

File

src/Entity/Storage/GroupContentStorage.php, line 88

Class

GroupContentStorage
Defines the storage handler class for group content entities.

Namespace

Drupal\group\Entity\Storage

Code

public function loadByEntity(ContentEntityInterface $entity) {

  // An unsaved entity cannot have any group content.
  $entity_id = $entity
    ->id();
  if ($entity_id === NULL) {
    throw new EntityStorageException("Cannot load GroupContent entities for an unsaved entity.");
  }
  $entity_type_id = $entity
    ->getEntityTypeId();
  if (!isset($this->loadByEntityCache[$entity_type_id][$entity_id])) {

    /** @var \Drupal\group\Entity\Storage\GroupContentTypeStorageInterface $storage */
    $storage = $this->entityTypeManager
      ->getStorage('group_content_type');
    $group_content_types = $storage
      ->loadByEntityTypeId($entity_type_id);

    // Statically cache all group content IDs for the group content types.
    if (!empty($group_content_types)) {

      // Use an optimized plain query to avoid the overhead of entity and SQL
      // query builders.
      $query = "SELECT id from {{$this->dataTable}} WHERE entity_id = :entity_id AND type IN (:types[])";
      $this->loadByEntityCache[$entity_type_id][$entity_id] = $this->database
        ->query($query, [
        ':entity_id' => $entity_id,
        ':types[]' => array_keys($group_content_types),
      ])
        ->fetchCol();
    }
    else {
      $this->loadByEntityCache[$entity_type_id][$entity_id] = [];
    }
  }
  if (!empty($this->loadByEntityCache[$entity_type_id][$entity_id])) {
    return $this
      ->loadMultiple($this->loadByEntityCache[$entity_type_id][$entity_id]);
  }
  else {
    return [];
  }
}