3 namespace Drupal\bootstrap\Plugin\Preprocess;
5 use Drupal\bootstrap\Bootstrap;
6 use Drupal\bootstrap\Utility\Element;
7 use Drupal\bootstrap\Utility\Variables;
10 use Drupal\file\Entity\File;
13 * Pre-processes variables for the "file_link" theme hook.
15 * @ingroup plugins_preprocess
17 * @BootstrapPreprocess("file_link",
18 * replace = "template_preprocess_file_link"
21 class FileLink extends PreprocessBase {
26 public function preprocessVariables(Variables $variables) {
29 $file = ($variables['file'] instanceof File) ? $variables['file'] : File::load($variables['file']->fid);
30 $url = file_create_url($file->getFileUri());
32 $file_size = $file->getSize();
33 $mime_type = $file->getMimeType();
35 // Set options as per anchor format described at
36 // http://microformats.org/wiki/file-format-examples
37 $options['attributes']['type'] = "$mime_type; length=$file_size";
39 // Use the description as the link text if available.
40 if (empty($variables['description'])) {
41 $link_text = $file->getFilename();
44 $link_text = $variables['description'];
45 $options['attributes']['title'] = $file->getFilename();
48 // Retrieve the generic mime type from core (mislabeled as "icon_class").
49 $generic_mime_type = file_icon_class($mime_type);
51 // Map the generic mime types to an icon and state.
53 'application-x-executable' => [
54 'label' => t('binary file'),
58 'label' => t('audio file'),
59 'icon' => 'headphones',
62 'label' => t('image'),
65 'package-x-generic' => [
66 'label' => t('archive'),
67 'icon' => 'compressed',
70 'label' => t('document'),
74 'label' => t('video'),
79 // Retrieve the mime map array.
80 $mime = isset($mime_map[$generic_mime_type]) ? $mime_map[$generic_mime_type] : [
86 // Classes to add to the file field for icons.
87 $variables->addClass([
89 // Add a specific class for each and every mime type.
90 'file--mime-' . strtr($mime_type, ['/' => '-', '.' => '-']),
91 // Add a more general class for groups of well known mime types.
92 'file--' . $generic_mime_type,
95 // Set the icon for the mime type.
96 $icon = Bootstrap::glyphicon($mime['icon']);
97 $variables->icon = Element::create($icon)
98 ->addClass('text-primary')
101 $options['attributes']['title'] = t('Open @mime in new window', ['@mime' => $mime['label']]);
102 $options['attributes']['target'] = '_blank';
104 if ($this->theme->getSetting('tooltip_enabled')) {
105 $options['attributes']['data-toggle'] = 'tooltip';
106 $options['attributes']['data-placement'] = 'bottom';
108 $variables['link'] = Link::fromTextAndUrl($link_text, Url::fromUri($url, $options));
110 // Add the file size as a variable.
111 $variables->file_size = format_size($file_size);
113 // Preprocess attributes.
114 $this->preprocessAttributes();