You are here

function template_preprocess_minisite_link in Mini site 8

Prepares variables for minisite link templates.

Default template: minisite-link.html.twig.

Parameters

array $variables: An associative array containing:

  • file: A file object to which the link will be created.
  • asset_path: Path to the first asset in the minisite.
  • icon_directory: (optional) A path to a directory of icons to be used for files. Defaults to the value of the "icon.directory" variable.
  • description: A description to be displayed instead of the filename.
  • attributes: An associative array of attributes to be placed in the a tag.

File

./minisite.theme.inc, line 80
minisite.theme.inc

Code

function template_preprocess_minisite_link(array &$variables) {
  $variables['attributes'] = new Attribute($variables['attributes']);
  $file = $variables['file'];
  $options = [];
  $file_entity = $file instanceof File ? $file : File::load($file->fid);

  // @todo Wrap in file_url_transform_relative(). This is currently
  // impossible. As a work-around, we currently add the 'url.site' cache context
  // to ensure different file URLs are generated for different sites in a
  // multisite setup, including HTTP and HTTPS versions of the same site.
  // Fix in https://www.drupal.org/node/2646744.
  $variables['#cache']['contexts'][] = 'url.site';
  $link_text = $file_entity
    ->getFilename();

  // Asset path is provided.
  if (isset($variables['asset_path'])) {

    // Asset path is a file.
    if (LegacyWrapper::isValidUri($variables['asset_path'])) {
      $url = file_create_url($variables['asset_path']);
    }
    else {
      $url = Url::fromUserInput($variables['asset_path'])
        ->toString();
    }

    // Use the description as the link text if available.
    if (!empty($variables['description'])) {
      $link_text = $variables['description'];
    }
  }
  else {
    $url = file_create_url($file_entity
      ->getFileUri());
    $mime_type = $file
      ->getMimeType();

    // Set options as per anchor format described at
    // http://microformats.org/wiki/file-format-examples
    $options['attributes']['type'] = $mime_type . '; length=' . $file
      ->getSize();

    // Classes to add to the file field for icons.
    $classes = [
      'file',
      // Add a specific class for each and every mime type.
      'file--mime-' . strtr($mime_type, [
        '/' => '-',
        '.' => '-',
      ]),
      // Add a more general class for groups of well known MIME types.
      'file--' . file_icon_class($mime_type),
    ];
    $variables['attributes']
      ->addClass($classes);
  }

  // Set link title.
  $options['attributes']['title'] = $link_text;
  $variables['link'] = Link::fromTextAndUrl($link_text, Url::fromUserInput($url, $options));
}