You are here

function metatag_tokens in Metatag 8

Same name and namespace in other branches
  1. 7 metatag.tokens.inc \metatag_tokens()

Implements hook_tokens().

File

./metatag.tokens.inc, line 126
Metatag token integration.

Code

function metatag_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  switch ($type) {
    case 'current-page':

      /** @var \Drupal\token\TokenInterface $token_service */
      $token_service = \Drupal::token();
      $metatag_tokens = $token_service
        ->findWithPrefix($tokens, 'metatag');
      if (!empty($metatag_tokens) && metatag_is_current_route_supported()) {

        // Add cache contexts to ensure this token functions on a per-path
        // basis.
        $bubbleable_metadata
          ->addCacheContexts([
          'url.site',
        ]);
        $replacements += $token_service
          ->generate('metatag', $metatag_tokens, [], $options, $bubbleable_metadata);
      }
      break;
    case 'entity':
      if (!empty($data['entity_type']) && !empty($data['entity']) && !empty($data['token_type'])) {

        /* @var \Drupal\Core\Entity\ContentEntityInterface $entity */
        $entity = $data['entity'];
        if (!$entity instanceof ContentEntityInterface) {
          return $replacements;
        }
        $metatag_fields = [];
        foreach ($tokens as $name => $original) {
          $field_name = explode(':', $name)[0];
          if ($entity
            ->hasField($field_name) && $entity
            ->get($field_name)
            ->getFieldDefinition()
            ->getType() === 'metatag') {
            $metatag_fields[] = $field_name;
          }
        }
        if (!empty($metatag_fields)) {

          /** @var \Drupal\token\TokenInterface $token_service */
          $token_service = \Drupal::token();
          $metatag_tokens = [];
          foreach ($metatag_fields as $metatag_field) {
            $metatag_tokens += $token_service
              ->findWithPrefix($tokens, $metatag_field);
          }
          $replacements += $token_service
            ->generate('metatag', $metatag_tokens, [
            'entity' => $entity,
          ], $options, $bubbleable_metadata);
        }
      }
      break;
    case 'metatag':
      $metatag_manager = \Drupal::service('metatag.manager');
      $entity = $options['entity'] ?? metatag_get_route_entity();
      $tags = metatag_get_default_tags($entity);
      if ($entity instanceof ContentEntityInterface) {

        // If content entity does not have an ID the page is likely an "Add"
        // page, so skip processing for entity which has not been created yet.
        if (!$entity
          ->id()) {
          return NULL;
        }
        $tags += $metatag_manager
          ->tagsFromEntity($entity);
      }

      // Trigger hook_metatags_alter().
      // Allow modules to override tags or the entity used for token
      // replacements.
      $context = [
        'entity' => &$entity,
      ];
      \Drupal::service('module_handler')
        ->alter('metatags', $tags, $context);

      // If the entity was changed above, use that for generating the meta tags.
      if (isset($context['entity'])) {
        $entity = $context['entity'];
      }
      $processed_tags = $metatag_manager
        ->generateTokenValues($tags, $entity);
      foreach ($tokens as $name => $original) {

        // For the [metatag:tag_name] token.
        if (strpos($name, ':') === FALSE) {
          $tag_name = $name;
        }
        else {
          list($tag_name, $delta) = explode(':', $name, 2);
          if (!is_numeric($delta)) {
            unset($delta);
          }
        }

        // Replace dashes (-) with underscores (_) for e.g. canonical-url.
        $tag_name = str_replace('-', '_', $tag_name);
        if (empty($processed_tags[$tag_name])) {
          continue;
        }

        // Render only one delta.
        if (isset($delta)) {
          $replacements[$original] = $processed_tags[$tag_name][$delta] ?? NULL;
        }
        else {
          if (is_array($processed_tags[$tag_name])) {
            $replacements[$original] = implode(',', $processed_tags[$tag_name]);
          }
          else {
            $replacements[$original] = $processed_tags[$tag_name];
          }
        }
      }
      break;
  }
  return $replacements;
}