3 namespace Drupal\media_entity_document\Plugin\MediaEntity\Type;
5 use Drupal\media_entity\MediaInterface;
6 use Drupal\media_entity\MediaTypeBase;
7 use Drupal\Core\Form\FormStateInterface;
10 * Provides media type plugin for Document.
14 * label = @Translation("Document"),
15 * description = @Translation("Provides business logic and metadata for local documents.")
18 class Document extends MediaTypeBase {
23 public function providedFields() {
25 'mime' => $this->t('File MIME'),
26 'size' => $this->t('Size'),
33 public function getField(MediaInterface $media, $name) {
34 $source_field = $this->configuration['source_field'];
36 // Get the file document.
37 /** @var \Drupal\file\FileInterface $file */
38 $file = $media->{$source_field}->entity;
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'];
62 /** @var \Drupal\Core\Field\FieldDefinitionInterface $field */
63 foreach ($this->entityFieldManager->getFieldDefinitions('media', $bundle->id()) as $field_name => $field) {
64 if (in_array($field->getType(), $allowed_field_types) && !$field->getFieldStorageDefinition()->isBaseField()) {
65 $options[$field_name] = $field->getLabel();
69 $form['source_field'] = [
71 '#title' => $this->t('Field with source information'),
72 '#description' => $this->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.'),
73 '#default_value' => empty($this->configuration['source_field']) ? NULL : $this->configuration['source_field'],
74 '#options' => $options,
83 public function thumbnail(MediaInterface $media) {
84 $source_field = $this->configuration['source_field'];
85 /** @var \Drupal\file\FileInterface $file */
86 $file = $media->{$source_field}->entity;
89 $mimetype = $file->getMimeType();
90 $mimetype = explode('/', $mimetype);
91 $thumbnail = $this->config->get('icon_base') . "/{$mimetype[0]}-{$mimetype[1]}.png";
93 if (!is_file($thumbnail)) {
94 $thumbnail = $this->config->get('icon_base') . "/{$mimetype[1]}.png";
96 if (!is_file($thumbnail)) {
97 $thumbnail = $this->config->get('icon_base') . '/document.png';
102 $thumbnail = $this->config->get('icon_base') . '/document.png';
111 public function getDefaultName(MediaInterface $media) {
112 // The default name will be the filename of the source_field, if present.
113 $source_field = $this->configuration['source_field'];
115 /** @var \Drupal\file\FileInterface $file */
116 if (!empty($source_field) && ($file = $media->{$source_field}->entity)) {
117 return $file->getFilename();
120 return parent::getDefaultName($media);