MediaTypeGuesser.php in Gutenberg 8.2
File
src/MediaTypeGuesser.php
View source
<?php
namespace Drupal\gutenberg;
use Drupal\Core\Entity\EntityTypeManagerInterface;
class MediaTypeGuesser implements MediaTypeGuesserInterface {
protected $defaultMediaTypes = [
'image',
'audio',
'video',
'remote_video',
'file',
];
protected $entityTypeManager;
protected $fileExtensionGuesser;
public function __construct(EntityTypeManagerInterface $entity_type_manager, FileExtensionGuesserInterface $file_extension_guesser) {
$this->entityTypeManager = $entity_type_manager;
$this->fileExtensionGuesser = $file_extension_guesser;
}
public function guess(string $general_media_type, $return_option = self::RETURN_ALL) {
$file_extensions = $this->fileExtensionGuesser
->guessByGeneralMimeType($general_media_type);
$media_type_entities = $this->entityTypeManager
->getStorage('media_type')
->loadMultiple();
$media_types = [];
foreach ($media_type_entities as $media_type_entity) {
$field_config = $media_type_entity
->getSource()
->getSourceFieldDefinition($media_type_entity);
$media_type_file_extensions = explode(' ', $field_config
->getSetting('file_extensions'));
if (array_intersect($media_type_file_extensions, $file_extensions)) {
$media_types[] = $media_type_entity
->id();
}
}
if ($return_option === self::RETURN_ALL) {
return $media_types;
}
if ($return_option === self::RETURN_NEGOTIATED) {
return $this
->negotiateMediaTypes($media_types);
}
throw new \InvalidArgumentException('Invalid guesser return type provided.');
}
public function negotiateMediaTypes(array $media_types) {
if (!$media_types) {
return '';
}
if ($default_media_types = array_intersect($this->defaultMediaTypes, $media_types)) {
return reset($default_media_types);
}
return reset($media_types);
}
}