You are here

token_custom.module in Custom Tokens 8

Hooks for Custom Tokens module.

File

token_custom.module
View source
<?php

/**
 * @file
 * Hooks for Custom Tokens module.
 */
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\TypedData\TranslatableInterface;
use Drupal\token_custom\Entity\TokenCustom;
use Drupal\token_custom\Entity\TokenCustomType;
use Drupal\Core\Language\Language;

/**
 * Implements hook_token_info().
 */
function token_custom_token_info() {
  $types = [];
  foreach (TokenCustomType::loadMultiple() as $token_type) {
    $types[$token_type
      ->id()] = [
      'name' => $token_type->name,
      'description' => $token_type->description,
    ];
  }
  $tokens = [];
  foreach (TokenCustom::loadMultiple() as $token) {
    $tokens[$token
      ->bundle()][$token
      ->id()] = [
      'name' => $token
        ->label(),
      'description' => $token
        ->getDescription(),
    ];
  }
  return [
    'types' => $types,
    'tokens' => $tokens,
  ];
}

/**
 * Implements hook_tokens().
 */
function token_custom_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  $token_customs = TokenCustom::loadMultiple(array_keys($tokens));
  foreach ($token_customs as $machine_name => $token_custom) {
    if ($type == $token_custom
      ->bundle() && array_key_exists($machine_name, $tokens)) {
      if ($token_custom instanceof TranslatableInterface) {
        $langcode = isset($options['langcode']) ? $options['langcode'] : Language::LANGCODE_DEFAULT;
        $token_custom = \Drupal::service('entity.repository')
          ->getTranslationFromContext($token_custom, $langcode);
      }
      $replacements[$tokens[$machine_name]] = $token_custom
        ->getFormattedContent();
      $bubbleable_metadata
        ->addCacheableDependency($token_custom);
    }
  }
  return $replacements;
}

Functions