You are here

function youtube_tokens in YouTube Field 8

Same name and namespace in other branches
  1. 7 youtube.inc \youtube_tokens()

Implements hook_tokens().

See also

youtube_tokens_info_alter()

File

./youtube.module, line 514
Youtube field module adds a field for YouTube videos.

Code

function youtube_tokens($type, $tokens, array $data = [], array $options = []) {
  global $base_url;
  global $base_path;
  $url_options = [
    'absolute' => TRUE,
  ];
  if (isset($options['langcode'])) {
    $url_options['language'] = \Drupal::languageManager()
      ->getLanguage($options['langcode']);
    $langcode = $options['langcode'];
  }
  else {
    $langcode = LanguageInterface::LANGCODE_DEFAULT;
  }
  $sanitize = !empty($options['sanitize']);
  $replacements = [];
  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];
    foreach ($tokens as $name => $original) {
      if (!strpos($name, '__youtube_')) {

        // This isn't a youtube token!
        continue;
      }
      $token_pieces = explode('__', $name);
      if (count($token_pieces) != 2) {
        continue;
      }
      $field_name = $token_pieces[0];
      $token_name = $token_pieces[1];
      switch ($token_name) {
        case 'youtube_video_url':
          $replacements[$original] = '';
          $field = $node->{$field_name};
          if ($video_id = $field->video_id) {
            $replacements[$original] = 'http://www.youtube.com/watch?v=' . $video_id;
          }
          break;
        case 'youtube_image_url':
          $replacements[$original] = '';
          $field = $node->{$field_name};
          if ($video_id = $field->video_id) {
            $file_uri = youtube_build_thumbnail_uri($video_id);
            if (file_exists($file_uri) || youtube_get_remote_image($video_id)) {
              $replacements[$original] = file_create_url($file_uri);
              if ($style_name = \Drupal::config('youtube.settings')
                ->get('youtube_thumb_token_image_style')) {
                $image_style = ImageStyle::load($style_name);
                $derivative_uri = $image_style
                  ->buildUri($file_uri);
                if (!file_exists($derivative_uri)) {
                  $image_style
                    ->createDerivative($file_uri, $derivative_uri);
                }
                $replacements[$original] = file_create_url($derivative_uri);
              }
            }
          }
          break;
      }
    }
  }
  return $replacements;
}