class MediaUploader in Gutenberg 8
Same name and namespace in other branches
- 8.2 src/MediaUploader.php \Drupal\gutenberg\MediaUploader
Upload files from Gutenberg editor upload method.
@package Drupal\gutenberg
Hierarchy
- class \Drupal\gutenberg\MediaUploader implements MediaUploaderInterface
Expanded class hierarchy of MediaUploader
1 string reference to 'MediaUploader'
1 service uses MediaUploader
File
- src/
MediaUploader.php, line 15
Namespace
Drupal\gutenbergView source
class MediaUploader implements MediaUploaderInterface {
/**
* The file system service.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* MediaUploader constructor.
*
* @param \Drupal\Core\File\FileSystemInterface $file_system
* The file system service.
*/
public function __construct(FileSystemInterface $file_system) {
$this->fileSystem = $file_system;
}
/**
* {@inheritDoc}
*/
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;
}
/**
* Generate random file name.
*
* @param \Drupal\gutenberg\string $extension
* (optional) File extension.
*
* @return string
* The file name.
*/
protected function getRandomFileName(string $extension = '') {
$name = (new Random())
->name(50, TRUE);
return $extension ? sprintf('%s.%s', $name, $extension) : $name;
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
MediaUploader:: |
protected | property | The file system service. | |
MediaUploader:: |
protected | function | Generate random file name. | |
MediaUploader:: |
public | function |
Upload media to the filesystem. Overrides MediaUploaderInterface:: |
|
MediaUploader:: |
public | function | MediaUploader constructor. |