You are here

function relation_rules_fetch_endpoint in Relation 8

Same name and namespace in other branches
  1. 8.2 relation.rules.inc \relation_rules_fetch_endpoint()
  2. 7 relation.rules.inc \relation_rules_fetch_endpoint()

Action callback fetching a given number of endpoint entities for a particular relation.

File

./relation.rules.inc, line 421
Implements the Rules module API for Relation.

Code

function relation_rules_fetch_endpoint($relation, $entity_type, $number = 1) {

  // Make sure we have the fully loaded relation entity.
  $loaded_relation = Relation::load($relation
    ->id());

  // Load the endpoints.
  $endpoints = field_get_items($loaded_relation, 'endpoints');
  $entity_ids = array();
  foreach ($endpoints as $endpoint) {

    // We only want to return entities of the selected type.
    if (!empty($endpoint['entity_type']) && $entity_type == $endpoint['entity_type']) {
      $entity_ids[] = $endpoint['entity_id'];
      if ($number == count($entity_ids)) {
        break;
      }
    }
  }
  if ($entity_ids) {
    $storage_handler = \Drupal::entityTypeManager()
      ->getStorage($entity_type);
    $return = $storage_handler
      ->loadMultiple($entity_ids);

    // Return a list unless we are only supposed to return a single entity.
    if (1 == $number) {
      $return = reset($return);
      if (!$return) {
        throw new RulesEvaluationException('Unable to load relation endpoint of type "@type" for @entity with id "@id".', array(
          '@type' => $entity_type,
          '@entity' => $relation->relation_type,
          '@id' => $relation
            ->id(),
        ));
      }
    }
    return array(
      'endpoint_fetched' => $return,
    );
  }

  // We didn't find any entities in the relation that matched the provided conditions.
  return NULL;
}