4 * Contains \Drupal\bootstrap\Plugin\Preprocess\FileLink.
7 namespace Drupal\bootstrap\Plugin\Preprocess;
9 use Drupal\bootstrap\Annotation\BootstrapPreprocess;
10 use Drupal\bootstrap\Bootstrap;
11 use Drupal\bootstrap\Utility\Element;
12 use Drupal\bootstrap\Utility\Variables;
15 use Drupal\file\Entity\File;
18 * Pre-processes variables for the "file_link" theme hook.
20 * @ingroup plugins_preprocess
22 * @BootstrapPreprocess("file_link",
23 * replace = "template_preprocess_file_link"
26 class FileLink extends PreprocessBase {
31 public function preprocessVariables(Variables $variables) {
34 $file = ($variables['file'] instanceof File) ? $variables['file'] : File::load($variables['file']->fid);
35 $url = file_create_url($file->getFileUri());
37 $file_size = $file->getSize();
38 $mime_type = $file->getMimeType();
40 // Set options as per anchor format described at
41 // http://microformats.org/wiki/file-format-examples
42 $options['attributes']['type'] = "$mime_type; length=$file_size";
44 // Use the description as the link text if available.
45 if (empty($variables['description'])) {
46 $link_text = $file->getFilename();
49 $link_text = $variables['description'];
50 $options['attributes']['title'] = $file->getFilename();
53 // Retrieve the generic mime type from core (mislabeled as "icon_class").
54 $generic_mime_type = file_icon_class($mime_type);
56 // Map the generic mime types to an icon and state.
58 'application-x-executable' => [
59 'label' => t('binary file'),
63 'label' => t('audio file'),
64 'icon' => 'headphones',
67 'label' => t('image'),
70 'package-x-generic' => [
71 'label' => t('archive'),
72 'icon' => 'compressed',
75 'label' => t('document'),
79 'label' => t('video'),
84 // Retrieve the mime map array.
85 $mime = isset($mime_map[$generic_mime_type]) ? $mime_map[$generic_mime_type] : [
91 // Classes to add to the file field for icons.
92 $variables->addClass([
94 // Add a specific class for each and every mime type.
95 'file--mime-' . strtr($mime_type, ['/' => '-', '.' => '-']),
96 // Add a more general class for groups of well known mime types.
97 'file--' . $generic_mime_type,
100 // Set the icon for the mime type.
101 $icon = Bootstrap::glyphicon($mime['icon']);
102 $variables->icon = Element::create($icon)
103 ->addClass('text-primary')
106 $options['attributes']['title'] = t('Open @mime in new window', ['@mime' => $mime['label']]);
107 $options['attributes']['target'] = '_blank';
109 if ($this->theme->getSetting('tooltip_enabled')) {
110 $options['attributes']['data-toggle'] = 'tooltip';
111 $options['attributes']['data-placement'] = 'bottom';
113 $variables['link'] = Link::fromTextAndUrl($link_text, Url::fromUri($url, $options));
115 // Add the file size as a variable.
116 $variables->file_size = format_size($file_size);
118 // Preprocess attributes.
119 $this->preprocessAttributes();