b6ad9799e8e84b4f8da328ab02b43e105f99d222
[yaffs-website] / web / core / modules / media / src / Plugin / media / Source / File.php
1 <?php
2
3 namespace Drupal\media\Plugin\media\Source;
4
5 use Drupal\file\FileInterface;
6 use Drupal\media\MediaInterface;
7 use Drupal\media\MediaTypeInterface;
8 use Drupal\media\MediaSourceBase;
9
10 /**
11  * File entity media source.
12  *
13  * @see \Drupal\file\FileInterface
14  *
15  * @MediaSource(
16  *   id = "file",
17  *   label = @Translation("File"),
18  *   description = @Translation("Use local files for reusable media."),
19  *   allowed_field_types = {"file"},
20  *   default_thumbnail_filename = "generic.png"
21  * )
22  */
23 class File extends MediaSourceBase {
24
25   /**
26    * {@inheritdoc}
27    */
28   public function getMetadataAttributes() {
29     return [];
30   }
31
32   /**
33    * {@inheritdoc}
34    */
35   public function getMetadata(MediaInterface $media, $attribute_name) {
36     /** @var \Drupal\file\FileInterface $file */
37     $file = $media->get($this->configuration['source_field'])->entity;
38     // If the source field is not required, it may be empty.
39     if (!$file) {
40       return parent::getMetadata($media, $attribute_name);
41     }
42     switch ($attribute_name) {
43       case 'default_name':
44         return $file->getFilename();
45
46       case 'thumbnail_uri':
47         return $this->getThumbnail($file) ?: parent::getMetadata($media, $attribute_name);
48
49       default:
50         return parent::getMetadata($media, $attribute_name);
51     }
52   }
53
54   /**
55    * Gets the thumbnail image URI based on a file entity.
56    *
57    * @param \Drupal\file\FileInterface $file
58    *   A file entity.
59    *
60    * @return string
61    *   File URI of the thumbnail image or NULL if there is no specific icon.
62    */
63   protected function getThumbnail(FileInterface $file) {
64     $icon_base = $this->configFactory->get('media.settings')->get('icon_base_uri');
65
66     // We try to automatically use the most specific icon present in the
67     // $icon_base directory, based on the MIME type. For instance, if an
68     // icon file named "pdf.png" is present, it will be used if the file
69     // matches this MIME type.
70     $mimetype = $file->getMimeType();
71     $mimetype = explode('/', $mimetype);
72
73     $icon_names = [
74       $mimetype[0] . '--' . $mimetype[1],
75       $mimetype[1],
76       $mimetype[0],
77     ];
78     foreach ($icon_names as $icon_name) {
79       $thumbnail = $icon_base . '/' . $icon_name . '.png';
80       if (is_file($thumbnail)) {
81         return $thumbnail;
82       }
83     }
84
85     return NULL;
86   }
87
88   /**
89    * {@inheritdoc}
90    */
91   public function createSourceField(MediaTypeInterface $type) {
92     return parent::createSourceField($type)->set('settings', ['file_extensions' => 'txt doc docx pdf']);
93   }
94
95 }