cms_content_sync-3.0.x-dev/cms_content_sync.tokens.inc

cms_content_sync.tokens.inc
<?php

/**
 * @file
 * Builds placeholder replacement tokens for cms_content_sync-related data.
 */

use Drupal\cms_content_sync\Entity\EntityStatus;
use Drupal\cms_content_sync\EntityStatusProxy;
use Drupal\Core\Render\BubbleableMetadata;

/**
 * Implements hook_token_info().
 */
function cms_content_sync_token_info() {
  $info = [];

  $info['types']['cms_content_sync'] = [
    'name' => t('CMS Content Sync'),
    'description' => t('CMS Content Sync related tokens'),
  ];

  $info['tokens']['cms_content_sync']['source_url'] = [
    'name' => t('Source URL'),
    'description' => t('The entities source URL. Only works for Nodes. Mostly used for the canonical URL.'),
  ];

  $info['tokens']['cms_content_sync']['source_url_untranslated'] = [
    'name' => t('Source URL (untranslated)'),
    'description' => t('The entities source URL in the entity\'s default language. Only works for Nodes. Mostly used for the canonical URL.'),
  ];

  return $info;
}

/**
 * Implements hook_tokens().
 */
function cms_content_sync_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  if ('cms_content_sync' == $type) {
    foreach ($tokens as $name => $original) {
      // Find the desired token by name.
      switch ($name) {
        case 'source_url_untranslated':
          $replacements[$original] = _cms_content_sync_tokens_source_url($data);

          break;

        case 'source_url':
          $replacements[$original] = _cms_content_sync_tokens_source_url($data, TRUE);

          break;
      }
    }
  }

  return $replacements;
}

/**
 * Token callback for the source_url.
 */
function _cms_content_sync_tokens_source_url($data, $translated = FALSE) {
  // Only support node entities.
  if (!empty($data['node'])) {
    /** @var \Drupal\node\NodeInterface $node */
    $node = $data['node'];

    $status_entities = EntityStatus::getInfosForEntity('node', $node->uuid());
    if (!empty($status_entities)) {
      $status_entity = new EntityStatusProxy($status_entities);
      $source_url = $translated ? $status_entity->getTranslationSourceUrl($node->language()->getId()) : $status_entity->getSourceUrl();

      if (!empty($source_url)) {
        return $source_url;
      }
    }

    // Copied from node.tokens.inc.
    $url_options = ['absolute' => TRUE];
    if (isset($options['langcode'])) {
      $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
    }

    // Return the node_url if no status_entity or no source_url is set.
    return $node->toUrl('canonical', $url_options)->toString();
  }

  return '';
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc