You are here

tokenuuid.module in Token UUID 8

Contains tokenuuid.module.

File

tokenuuid.module
View source
<?php

/**
 * @file
 * Contains tokenuuid.module.
 */
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Entity;

/**
 * Implements hook_help().
 */
function tokenuuid_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {

    // Main module help for the tokenuuid module.
    case 'help.page.tokenuuid':
      $output = '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Create an Universally unique identifier token for node, term, user, current-user and all others content entities.') . '</p>';
      $output .= '<ul>';
      $output .= '<li>[current-user:uuid]</li>';
      foreach (tokenuuid_get_contententitytype_id() as $entity_id) {
        $output .= '<li>[' . $entity_id . ':uuid]</li>';
      }
      $output .= '</ul>';
      return $output;
    default:
  }
}

/**
 * Implements hook_token_info().
 */
function tokenuuid_token_info() {
  $info['tokens'] = [];
  foreach (tokenuuid_get_contententitytype_id() as $entity_id) {
    $info['tokens'][$entity_id]['uuid'] = [
      'name' => t('@entity_id UUID', [
        '@entity_id' => $entity_id,
      ]),
      'description' => t('The Universal Unique Identifier of @entity_id', [
        '@entity_id' => $entity_id,
      ]),
    ];
  }
  return $info;
}

/**
 * Implements hook_tokens().
 *
 * @param string $type machine name of the group (type)
 * @param array $tokens tokens to be replaced.
 * @param array $data An associative array of data objects
 * @param array $options An associative array of options for token replacement
 * @param \Drupal\Core\Render\BubbleableMetadata $bubbleableMetadata
 *
 * @return array  associative keyed by [type:token] strings
 */
function tokenuuid_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleableMetadata) {
  foreach (tokenuuid_get_contententitytype_id() as $entity_id) {
    if ($type == $entity_id && !empty($data[$entity_id])) {
      $entity = $data[$entity_id];
      $replaced = [];
      foreach ($tokens as $name => $original) {
        if ($name == 'uuid') {
          $replaced[$original] = $entity
            ->uuid();
        }
      }
      return $replaced;
    }
  }
}

/**
 * @return array  list of entities type IDs keyed by entity group
 */
function tokenuuid_get_contententitytype_id() {
  $entity_types = [];
  $definitions = \Drupal::entityTypeManager()
    ->getDefinitions();
  foreach ($definitions as $definition) {
    if ($definition instanceof Entity\ContentEntityType) {
      $entity_types[] = $definition
        ->id();
    }
  }
  return $entity_types;
}