MediaMigrationUuidOracle.php in Media Migration 8
File
src/MediaMigrationUuidOracle.php
View source
<?php
namespace Drupal\media_migration;
use Drupal\Component\Uuid\UuidInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\DatabaseExceptionWrapper;
use Drupal\Core\Entity\EntityTypeManagerInterface;
final class MediaMigrationUuidOracle implements MediaMigrationUuidOracleInterface {
protected $database;
protected $mediaStorage;
protected $uuidGenerator;
public function __construct(Connection $database, EntityTypeManagerInterface $entity_type_manager, UuidInterface $uuid_generator) {
$this->database = $database;
$this->mediaStorage = $entity_type_manager
->getStorage('media');
$this->uuidGenerator = $uuid_generator;
}
public function getMediaUuid(int $source_id, bool $generate = TRUE) : ?string {
if ($media = $this->mediaStorage
->load($source_id)) {
return $media
->uuid();
}
if (!($uuid_prophecy = $this
->getMediaUuidProphecy($source_id)) && $generate) {
$uuid_prophecy = $this
->setMediaProphecy($source_id);
}
return $uuid_prophecy;
}
private function getMediaUuidProphecy(int $source_id) : ?string {
$results = $this->database
->select(MediaMigration::MEDIA_UUID_PROPHECY_TABLE, 'mupt')
->fields('mupt')
->condition('mupt.' . MediaMigration::MEDIA_UUID_PROPHECY_SOURCEID_COL, $source_id)
->execute()
->fetchAll();
return isset($results[0]->{MediaMigration::MEDIA_UUID_PROPHECY_UUID_COL}) ? $results[0]->{MediaMigration::MEDIA_UUID_PROPHECY_UUID_COL} : NULL;
}
private function setMediaProphecy(int $source_id) {
$uuid = $this->uuidGenerator
->generate();
try {
$this->database
->insert(MediaMigration::MEDIA_UUID_PROPHECY_TABLE)
->fields([
MediaMigration::MEDIA_UUID_PROPHECY_SOURCEID_COL => $source_id,
MediaMigration::MEDIA_UUID_PROPHECY_UUID_COL => $uuid,
])
->execute();
return $uuid;
} catch (DatabaseExceptionWrapper $e) {
throw new \LogicException(sprintf('Cannot create prophecy for the media entity with source id %i', $source_id));
}
}
}