You are here

public function ConnectionService::getConnectedEntities in RedHen CRM 8

Returns the other entities that are connected to this entity.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity we're querying against.

string $connection_type: (optional) Limit returned entities to ones connected via this type.

Return value

array The connected entities for this entity.

Overrides ConnectionServiceInterface::getConnectedEntities

File

modules/redhen_connection/src/ConnectionService.php, line 143

Class

ConnectionService
Provides an interface for getting connections between entities.

Namespace

Drupal\redhen_connection

Code

public function getConnectedEntities(EntityInterface $entity, $connection_type = NULL) {
  $connected_entities = [];
  $type = ConnectionType::load($connection_type);

  // Get all fields that reference endpoints on the connection type.
  $fields = $type
    ->getAllEndpointFields();

  // Get connections.
  $connections = $this
    ->getConnections($entity, NULL, $connection_type);

  // Loop through connections to find entities referenced by endpoint fields.
  foreach ($connections as $connection) {
    foreach ($fields as $field) {
      $referenced_entities = $connection
        ->get($field)
        ->referencedEntities();
      foreach ($referenced_entities as $referenced_entity) {

        // Do not include the entity originally passed in function args.
        if ($referenced_entity
          ->getEntityType()
          ->id() == $entity
          ->getEntityType()
          ->id() && $referenced_entity
          ->id() == $entity
          ->id()) {
          continue;
        }
        $connected_entities[] = $referenced_entity;
      }
    }
  }
  return $connected_entities;
}