MediaTypeManager.php in Media Bulk Upload 8
File
src/MediaTypeManager.php
View source
<?php
namespace Drupal\media_bulk_upload;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\media\MediaTypeInterface;
use Drupal\media_bulk_upload\Entity\MediaBulkConfigInterface;
class MediaTypeManager implements MediaTypeManagerInterface {
protected $mediaTypeExtensions;
protected $entityTypeManager;
protected $entityFieldManager;
public function __construct(EntityTypeManagerInterface $entityTypeManager, EntityFieldManagerInterface $entityFieldManager) {
$this->entityTypeManager = $entityTypeManager;
$this->entityFieldManager = $entityFieldManager;
$mediaTypes = $entityTypeManager
->getStorage('media_type')
->loadMultiple();
$this
->groupMediaTypes($mediaTypes);
}
private function groupMediaTypes($mediaTypes) {
foreach ($mediaTypes as $mediaType) {
$this
->processMediaTypeExtensions($mediaType);
}
return $this;
}
private function processMediaTypeExtensions(MediaTypeInterface $mediaType) {
foreach ($this
->getMediaTypeExtensions($mediaType) as $extension) {
$this->mediaTypeExtensions[$extension][$mediaType
->id()] = $mediaType;
}
}
public function getMediaTypeExtensions(MediaTypeInterface $mediaType) {
return $this
->getTargetFieldExtensions($this
->getTargetFieldSettings($mediaType));
}
public function getTargetFieldExtensions(array $targetFieldSettings) {
$extensions = isset($targetFieldSettings['file_extensions']) ? $targetFieldSettings['file_extensions'] : '';
return array_map('trim', explode(' ', $extensions));
}
public function getTargetFieldSettings(MediaTypeInterface $mediaType) {
$fieldDefinitions = $this->entityFieldManager
->getFieldDefinitions('media', $mediaType
->id());
$targetFieldName = $this
->getTargetFieldName($mediaType);
$targetField = $fieldDefinitions[$targetFieldName];
return $targetField
->getSettings();
}
public function getTargetFieldName(MediaTypeInterface $mediaType) {
return $mediaType
->getSource()
->getConfiguration()['source_field'];
}
public function getMediaTypeIdsByFileExtension($extension) {
if (!isset($this->mediaTypeExtensions[$extension])) {
throw new \Exception('No matching media type id for the given file.');
}
return $this->mediaTypeExtensions[$extension];
}
public function getTargetFieldMaxSize(MediaTypeInterface $mediaType) {
$targetFieldSettings = $this
->getTargetFieldSettings($mediaType);
$filesize = isset($targetFieldSettings['max_filesize']) ? $targetFieldSettings['max_filesize'] : '';
return $filesize;
}
public function getBulkMediaTypes(MediaBulkConfigInterface $mediaBulkConfig) {
$mediaTypeIds = $mediaBulkConfig
->get('media_types');
return $this->entityTypeManager
->getStorage('media_type')
->loadMultiple($mediaTypeIds);
}
}