Created
June 17, 2022 09:27
-
-
Save nonom/9272641e64799201bfd636af305ddb7d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\ema_document\Plugin\media\Source; | |
use Drupal\file\FileInterface; | |
use Drupal\media\MediaInterface; | |
use Drupal\media\MediaTypeInterface; | |
use Drupal\media\MediaSourceBase; | |
use Drupal\media\Plugin\media\Source\File as FileBase; | |
/** | |
* Extends the File entity media source. | |
* | |
* @see \Drupal\file\FileInterface | |
* | |
* @MediaSource( | |
* id = "file", | |
* label = @Translation("File"), | |
* description = @Translation("Use local files for reusable media."), | |
* allowed_field_types = {"file"}, | |
* default_thumbnail_filename = "generic.png" | |
* ) | |
*/ | |
class File extends FileBase { | |
/** | |
* Key for "Published" metadata attribute. | |
* | |
* @var string | |
*/ | |
const METADATA_ATTRIBUTE_DATE_PUBLISHED = 'published'; | |
/** | |
* Key for "Updated" metadata attribute. | |
* | |
* @var string | |
*/ | |
const METADATA_ATTRIBUTE_DATE_UPDATED = 'update'; | |
/** | |
* Key for "Example" metadata attribute. | |
* | |
* @var string | |
*/ | |
const METADATA_ATTRIBUTE_EXAMPLE_HERE = 'example'; | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getMetadataAttributes() { | |
// Add attributes. | |
return parent::getMetadataAttributes() + [ | |
static::METADATA_ATTRIBUTE_DATE_PUBLISHED => $this->t('Published'), | |
static::METADATA_ATTRIBUTE_DATE_UPDATED => $this->t('Updated'), | |
static::METADATA_ATTRIBUTE_EXAMPLE_HERE => $this->t('Example'), | |
]; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getMetadata(MediaInterface $media, $attribute_name) { | |
/** @var \Drupal\file\FileInterface $file */ | |
$file = $media->get($this->configuration['source_field'])->entity; | |
// If the source field is not required, it may be empty. | |
if (!$file) { | |
return parent::getMetadata($media, $attribute_name); | |
} | |
switch ($attribute_name) { | |
// Using the example attribute. | |
case static::METADATA_ATTRIBUTE_EXAMPLE_HERE: | |
return $file->getFilename(); | |
// Inherits the default behaviour | |
default: | |
return parent::getMetadata($media, $attribute_name); | |
} | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function createSourceField(MediaTypeInterface $type) { | |
return parent::createSourceField($type)->set('settings', [ | |
'file_extensions' => 'pdf', | |
]); | |
} | |
} |
Author
nonom
commented
Jun 17, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment