MediaTypePersistenceManager.php in Gutenberg 8.2
File
src/Persistence/MediaTypePersistenceManager.php
View source
<?php
namespace Drupal\gutenberg\Persistence;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\file\Entity\File;
class MediaTypePersistenceManager implements MediaTypePersistenceManagerInterface {
protected $entityTypeManager;
protected $account;
public function __construct(EntityTypeManagerInterface $entity_type_manager, AccountInterface $account) {
$this->entityTypeManager = $entity_type_manager;
$this->account = $account;
}
public function save(string $media_type, File $file_entity) {
$media_type_entity = $this->entityTypeManager
->getStorage('media_type')
->load($media_type);
$source = $media_type_entity
->getSource();
if (!$source) {
return NULL;
}
$field_config = $source
->getSourceFieldDefinition($media_type_entity);
$field_name = $field_config
->getName();
$media_entity = $this->entityTypeManager
->getStorage('media')
->create([
'bundle' => $media_type_entity
->id(),
'name' => $file_entity
->getFilename(),
'uid' => $this->account
->id(),
$field_name => [
'target_id' => $file_entity
->id(),
],
]);
try {
$media_entity
->save();
} catch (EntityStorageException $exception) {
return NULL;
}
return $media_entity;
}
public function getFileSettings(string $media_type) {
$media_type_entity = $this->entityTypeManager
->getStorage('media_type')
->load($media_type);
$source = $media_type_entity
->getSource();
$source_field_definition = $source
->getSourceFieldDefinition($media_type_entity);
if ($source_field_definition) {
return $source_field_definition
->getSettings();
}
return [];
}
}