You are here

public function MediaUploader::upload in Gutenberg 8

Same name and namespace in other branches
  1. 8.2 src/MediaUploader.php \Drupal\gutenberg\MediaUploader::upload()

Upload media to the filesystem.

Parameters

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

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

Return value

\Drupal\file\Entity\File|null File entity or null on failure.

Overrides MediaUploaderInterface::upload

File

src/MediaUploader.php, line 37

Class

MediaUploader
Upload files from Gutenberg editor upload method.

Namespace

Drupal\gutenberg

Code

public function upload(UploadedFile $uploaded_file, Editor $editor) {
  $image_settings = $editor
    ->getImageUploadSettings();
  $directory = "{$image_settings['scheme']}://{$image_settings['directory']}";
  if (!$this->fileSystem
    ->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY)) {
    return NULL;
  }

  // @todo: find better solution for saving file itself.
  $data = file_get_contents($uploaded_file
    ->getPathname());
  $file_name = $this
    ->getRandomFileName($uploaded_file
    ->getClientOriginalExtension() ?: '');
  $file = file_save_data($data, "{$directory}/{$file_name}", FileSystemInterface::EXISTS_RENAME);
  $file
    ->setTemporary();
  $file
    ->setFilename($uploaded_file
    ->getClientOriginalName());
  try {
    $file
      ->save();
  } catch (\Throwable $exception) {
    return NULL;
  }
  return $file;
}