You are here

function token_insert_entity_tokens in Token Insert Entity 7

Implements hook_tokens().

File

./token_insert_entity.module, line 87
Hook implementations for token_insert_entity module.

Code

function token_insert_entity_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $entity_titles = _token_insert_entity_entity_type_titles();
  foreach ($tokens as $name => $original) {

    // Since these tokens have extra metadata we need to match them instead of checking the $type.
    if (preg_match('/^\\[embed:(render|link)/', $original)) {
      $parts = explode(':', preg_replace('/(\\[|\\])/', '', $original));
      if ($parts[1] == 'render' && count($parts) == 5) {
        list(, , $view_mode, $entity_type, $id) = $parts;
        if (isset($entity_titles[$entity_type])) {

          // Embed a rendered entity.
          $entity = entity_load_single($entity_type, $id);
          if (entity_access('view', $entity_type, $entity)) {
            $rendered_entity = entity_view($entity_type, array(
              $entity,
            ), $view_mode);
            $replacements[$original] = drupal_render($rendered_entity);
          }
        }
      }
      elseif ($parts[1] == 'link' && count($parts) == 4) {
        list(, , $entity_type, $id) = $parts;
        if (isset($entity_titles[$entity_type])) {

          // Link to an entity.
          $entity = entity_load_single($entity_type, $id);
          if (entity_access('view', $entity_type, $entity)) {
            $entity_uri = entity_uri($entity_type, $entity);
            $entity_type_titles = _token_insert_entity_entity_type_titles();
            $replacements[$original] = l(t($entity->{$entity_type_titles[$entity_type]}), $entity_uri['path']);
          }
        }
      }
    }
  }
  return $replacements;
}