2 namespace Drupal\media_entity_document\Plugin\MediaEntity\Type;
4 use Drupal\media_entity\MediaInterface;
5 use Drupal\media_entity\MediaTypeBase;
6 use Drupal\Core\Form\FormStateInterface;
9 * Provides media type plugin for Document.
13 * label = @Translation("Document"),
14 * description = @Translation("Provides business logic and metadata for local documents.")
17 class Document extends MediaTypeBase {
22 public function providedFields() {
24 'mime' => t('File MIME'),
32 public function getField(MediaInterface $media, $name) {
33 $source_field = $this->configuration['source_field'];
34 $property_name = $media->{$source_field}->first()->mainPropertyName();
36 // Get the file document.
37 /** @var \Drupal\file\FileInterface $file */
38 $file = $this->entityTypeManager->getStorage('file')->load($media->{$source_field}->first()->{$property_name});
43 return !$file->filemime->isEmpty() ? $file->getMimeType() : FALSE;
46 $size = $file->getSize();
47 return $size ? $size : FALSE;
56 public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
57 /** @var \Drupal\media_entity\MediaBundleInterface $bundle */
58 $bundle = $form_state->getFormObject()->getEntity();
60 $allowed_field_types = ['file'];
61 foreach ($this->entityFieldManager->getFieldDefinitions('media', $bundle->id()) as $field_name => $field) {
62 if (in_array($field->getType(), $allowed_field_types) && !$field->getFieldStorageDefinition()->isBaseField()) {
63 $options[$field_name] = $field->getLabel();
67 $form['source_field'] = [
69 '#title' => t('Field with source information'),
70 '#description' => t('Field on media entity that stores Document file. You can create a bundle without selecting a value for this dropdown initially. This dropdown can be populated after adding fields to the bundle.'),
71 '#default_value' => empty($this->configuration['source_field']) ? NULL : $this->configuration['source_field'],
72 '#options' => $options,
81 public function thumbnail(MediaInterface $media) {
82 $source_field = $this->configuration['source_field'];
83 /** @var \Drupal\file\FileInterface $file */
84 $file = $this->entityTypeManager->getStorage('file')->load($media->{$source_field}->target_id);
85 $mimetype = $file->getMimeType();
86 $mimetype = explode('/', $mimetype);
87 $thumbnail = $this->config->get('icon_base') . "/{$mimetype[0]}-{$mimetype[1]}.png";
89 if (!is_file($thumbnail)) {
90 $thumbnail = $this->config->get('icon_base') . "/{$mimetype[1]}.png";
92 if (!is_file($thumbnail)) {
93 $thumbnail = $this->config->get('icon_base') . '/document.png';