3 namespace Drupal\media\Plugin\media\Source;
5 use Drupal\file\FileInterface;
6 use Drupal\media\MediaInterface;
7 use Drupal\media\MediaTypeInterface;
8 use Drupal\media\MediaSourceBase;
11 * File entity media source.
13 * @see \Drupal\file\FileInterface
17 * label = @Translation("File"),
18 * description = @Translation("Use local files for reusable media."),
19 * allowed_field_types = {"file"},
20 * default_thumbnail_filename = "generic.png"
23 class File extends MediaSourceBase {
28 public function getMetadataAttributes() {
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.
40 return parent::getMetadata($media, $attribute_name);
42 switch ($attribute_name) {
44 return $file->getFilename();
47 return $this->getThumbnail($file) ?: parent::getMetadata($media, $attribute_name);
50 return parent::getMetadata($media, $attribute_name);
55 * Gets the thumbnail image URI based on a file entity.
57 * @param \Drupal\file\FileInterface $file
61 * File URI of the thumbnail image or NULL if there is no specific icon.
63 protected function getThumbnail(FileInterface $file) {
64 $icon_base = $this->configFactory->get('media.settings')->get('icon_base_uri');
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);
74 $mimetype[0] . '--' . $mimetype[1],
78 foreach ($icon_names as $icon_name) {
79 $thumbnail = $icon_base . '/' . $icon_name . '.png';
80 if (is_file($thumbnail)) {
91 public function createSourceField(MediaTypeInterface $type) {
92 return parent::createSourceField($type)->set('settings', ['file_extensions' => 'txt doc docx pdf']);