You are here

function relation_rules_fetch_endpoint in Relation 7

Same name and namespace in other branches
  1. 8.2 relation.rules.inc \relation_rules_fetch_endpoint()
  2. 8 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 414
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->rid);

  // Load the endpoints
  $endpoints = field_get_items('relation', $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) {

    // Rules expects items in a list to be indexed from zero not by the entity ID as entity_load()
    // provides the list. array_values($entities) works, but the order should match that of the
    // endpoint field which cannot be guaranteed from entity_load(). As such a new list is created
    // for the entities in the expected order.
    $entities = entity_load($entity_type, $entity_ids);
    $return = array();
    foreach ($entity_ids as $entities_id) {
      $return[] = $entities[$entities_id];
    }

    // 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->rid,
        ));
      }
    }
    return array(
      'endpoint_fetched' => $return,
    );
  }

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