Version 1
[yaffs-website] / web / core / modules / file / src / Plugin / Field / FieldFormatter / FilemimeFormatter.php
1 <?php
2
3 namespace Drupal\file\Plugin\Field\FieldFormatter;
4
5 use Drupal\Core\Field\FieldDefinitionInterface;
6 use Drupal\Core\Field\FieldItemInterface;
7 use Drupal\Core\Form\FormStateInterface;
8
9 /**
10  * Formatter to render the file MIME type, with an optional icon.
11  *
12  * @FieldFormatter(
13  *   id = "file_filemime",
14  *   label = @Translation("File MIME"),
15  *   field_types = {
16  *     "string"
17  *   }
18  * )
19  */
20 class FilemimeFormatter extends BaseFieldFileFormatterBase {
21
22   /**
23    * {@inheritdoc}
24    */
25   public static function isApplicable(FieldDefinitionInterface $field_definition) {
26     return parent::isApplicable($field_definition) && $field_definition->getName() === 'filemime';
27   }
28
29   /**
30    * {@inheritdoc}
31    */
32   public static function defaultSettings() {
33     $settings = parent::defaultSettings();
34
35     $settings['filemime_image'] = FALSE;
36
37     return $settings;
38   }
39
40   /**
41    * {@inheritdoc}
42    */
43   public function settingsForm(array $form, FormStateInterface $form_state) {
44     $form = parent::settingsForm($form, $form_state);
45
46     $form['filemime_image'] = [
47       '#title' => $this->t('Display an icon'),
48       '#description' => $this->t('The icon is representing the file type, instead of the MIME text (such as "image/jpeg")'),
49       '#type' => 'checkbox',
50       '#default_value' => $this->getSetting('filemime_image'),
51     ];
52
53     return $form;
54   }
55
56   /**
57    * {@inheritdoc}
58    */
59   protected function viewValue(FieldItemInterface $item) {
60     $value = $item->value;
61     if ($this->getSetting('filemime_image') && $value) {
62       $file_icon = [
63         '#theme' => 'image__file_icon',
64         '#file' => $item->getEntity(),
65       ];
66       return $file_icon;
67     }
68     return $value;
69   }
70
71 }