You are here

public function MediaService::processMediaEntityUpload in Gutenberg 8.2

Same name and namespace in other branches
  1. 8 src/Service/MediaService.php \Drupal\gutenberg\Service\MediaService::processMediaEntityUpload()

Save uploaded file, create file and media entity if possible.

Parameters

string $form_field_name: The file field name.

\Symfony\Component\HttpFoundation\File\UploadedFile $uploaded_file: Uploaded file instance.

\Drupal\editor\Entity\Editor $editor: Editor entity instance.

Return value

mixed The media entity data.

Throws

\Drupal\gutenberg\Service\FileEntityNotSavedException

\Drupal\gutenberg\Service\MediaEntityNotSavedException

\Drupal\gutenberg\Service\MediaEntityNotMatchedException

File

src/Service/MediaService.php, line 248

Class

MediaService
The media service class.

Namespace

Drupal\gutenberg\Service

Code

public function processMediaEntityUpload(string $form_field_name, UploadedFile $uploaded_file, Editor $editor) {
  $media_installed = $this->moduleHandler
    ->moduleExists('media');

  // Allow all media file types by default.
  $file_settings = [];
  if ($media_installed) {
    $mime_type_pieces = explode('/', $uploaded_file
      ->getClientMimeType());
    if (!($media_type = $this->mediaTypeGuesser
      ->guess(reset($mime_type_pieces), MediaTypeGuesserInterface::RETURN_NEGOTIATED))) {
      throw new MediaEntityNotMatchedException();
    }

    // Fetch settings to restrict the file extensions by the Media entity.
    $file_settings = $this->mediaTypePersisterManager
      ->getFileSettings($media_type);
  }

  /** @var \Drupal\file\Entity\File $file_entity */
  if (!($file_entity = $this->mediaUploader
    ->upload($form_field_name, $uploaded_file, $editor, $file_settings))) {
    throw new FileEntityNotSavedException();
  }
  if ($media_installed) {
    if (!($media_entity = $this->mediaTypePersisterManager
      ->save($media_type, $file_entity))) {
      throw new MediaEntityNotSavedException();
    }
    return $this->entityDataProviderManager
      ->getData('media', $file_entity, [
      'media_id' => $media_entity
        ->id(),
      'media_type' => $media_entity
        ->bundle(),
    ]);
  }
  return $this->entityDataProviderManager
    ->getData('file', $file_entity);
}