init commit

This commit is contained in:
Louis Elkner-Alfaro 2023-09-13 11:02:56 -07:00
commit 989918023b
3 changed files with 87 additions and 0 deletions

View file

@ -0,0 +1,5 @@
name: Agaric Migration Helpers
type: module
description: Provides helpers to migrate data into modern Drupal.
package: Agaric
core_version_requirement: ^9 || ^10

View file

@ -0,0 +1,4 @@
services:
agaric_migration_helpers.field_transformations:
class: Drupal\migration_helpers\MigrationHelperFieldTransformations
arguments: ['@entity_type.manager']

View file

@ -0,0 +1,78 @@
<?php
namespace Drupal\agaric_migration_helpers;
use Drupal\Core\Entity\EntityTypeManagerInterface;
class AgaricMigrationHelperFieldTransformations {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs an AgaricMigrationHelperFieldTransformations object.
*/
public function __construct(
EntityTypeManagerInterface $entity_type_manager
) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* Move data from file/image fields into media reference fields.
*
* Default transformation is image fields.
*/
public function fieldToMediaEntity($entity_type, $source_field_names, $media_field_name, $source_entity_bundles = NULL, $media_entity_bundle = 'image', $media_target_field = 'field_media_image') {
$media_entity_storage = $this->entityTypeManager->getStorage('media');
$source_entity_storage = $this->entityTypeManager->getStorage($entity_type);
$entity_query = $source_entity_storage->getQuery();
$group = $entity_query->orConditionGroup();
foreach ($source_field_names as $field) {
$group->exists($field);
}
$entity_query->condition($group);
if (!\is_null($source_entity_bundles)) {
$bundle_key = $source_entity_storage->getEntityType()->getKey('bundle');
$entity_query->condition($bundle_key, (array) $source_entity_bundles, 'IN');
}
$entity_query->accessCheck(FALSE);
$results = $entity_query->execute();
$entities = $source_entity_storage->loadMultiple($results);
foreach ($entities as $entity) {
$media_target_ids = [];
foreach ($source_field_names as $source_field_name) {
foreach ($entity->$source_field_name as $fieldItem) {
$entity_data = [
'bundle' => $media_entity_bundle,
'uid' => $entity->getOwnerId(),
'langcode' => $entity->language()->getId(),
'status' => 1,
];
foreach (\array_keys($fieldItem->getValue()) as $subfield) {
$entity_data[$media_target_field][$subfield] = $fieldItem->get($subfield)->getValue();
}
$media_entity = $media_entity_storage->create($entity_data);
$media_entity->save();
$media_target_ids[] = $media_entity->id();
}
}
$entity->set($media_field_name, $media_target_ids);
$entity->save();
}
}
}