You are here

function field_collection_tokens in Field collection 7

Implements hook_tokens().

File

./field_collection.tokens.inc, line 72
Provides host entity tokens for field_collection.module.

Code

function field_collection_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  // Provide a complete set of tokens for type == 'host', and a supplementary
  // token 'host' for type == 'field_collection_item'.
  if (($type === 'field_collection_item' || $type === 'host') && !empty($data['field_collection_item'])) {
    $collection = $data['field_collection_item'];

    // When saving revisions, only $collection->original has valid state about
    // its host entity.
    if (!empty($collection->original)) {
      $collection = $collection->original;
    }
    if ($type === 'field_collection_item') {
      if (!empty($tokens['host'])) {
        $replacements[$tokens['host']] = $collection
          ->hostEntityId();
      }
      if ($host_tokens = token_find_with_prefix($tokens, 'host')) {
        $replacements += token_generate('host', $host_tokens, $data, $options);
      }
    }
    else {

      // Mapping between token and the FieldCollectionItemEntity method used to
      // retrieve the token with.
      $token_method_map = array(
        'type' => 'hostEntityType',
        'bundle' => 'hostEntityBundle',
        'id' => 'hostEntityId',
        'delta' => 'delta',
      );
      $entity_types = field_collection_host_entity_types();
      foreach ($tokens as $name => $orig) {
        if (isset($token_method_map[$name])) {
          $replacements[$orig] = $collection
            ->{$token_method_map[$name]}();
        }

        // This replaces e.g. [host:node] and [host:user] with their respective
        // nid and uid.
        if (!empty($entity_types[$name])) {
          $replacements[$orig] = $collection
            ->hostEntityId();
        }
      }
      foreach ($entity_types as $entity_type => $entity_info) {
        if ($entity_tokens = token_find_with_prefix($tokens, $entity_type)) {
          $host = $collection
            ->hostEntity();
          $replacements += token_generate($entity_type, $entity_tokens, array(
            $entity_type => $host,
          ), $options);
        }
      }
    }
  }
  return $replacements;
}