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 {
26 * Key for "MIME type" metadata attribute.
30 const METADATA_ATTRIBUTE_MIME = 'mimetype';
33 * Key for "File size" metadata attribute.
37 const METADATA_ATTRIBUTE_SIZE = 'filesize';
43 public function getMetadataAttributes() {
45 static::METADATA_ATTRIBUTE_MIME => $this->t('MIME type'),
46 static::METADATA_ATTRIBUTE_SIZE => $this->t('File size'),
53 public function getMetadata(MediaInterface $media, $attribute_name) {
54 /** @var \Drupal\file\FileInterface $file */
55 $file = $media->get($this->configuration['source_field'])->entity;
56 // If the source field is not required, it may be empty.
58 return parent::getMetadata($media, $attribute_name);
60 switch ($attribute_name) {
62 return $file->getMimeType();
65 return $file->getSize();
68 return $file->getFilename();
71 return $this->getThumbnail($file) ?: parent::getMetadata($media, $attribute_name);
74 return parent::getMetadata($media, $attribute_name);
79 * Gets the thumbnail image URI based on a file entity.
81 * @param \Drupal\file\FileInterface $file
85 * File URI of the thumbnail image or NULL if there is no specific icon.
87 protected function getThumbnail(FileInterface $file) {
88 $icon_base = $this->configFactory->get('media.settings')->get('icon_base_uri');
90 // We try to automatically use the most specific icon present in the
91 // $icon_base directory, based on the MIME type. For instance, if an
92 // icon file named "pdf.png" is present, it will be used if the file
93 // matches this MIME type.
94 $mimetype = $file->getMimeType();
95 $mimetype = explode('/', $mimetype);
98 $mimetype[0] . '--' . $mimetype[1],
102 foreach ($icon_names as $icon_name) {
103 $thumbnail = $icon_base . '/' . $icon_name . '.png';
104 if (is_file($thumbnail)) {
115 public function createSourceField(MediaTypeInterface $type) {
116 return parent::createSourceField($type)->set('settings', ['file_extensions' => 'txt doc docx pdf']);