image_to_media_swapper-2.x-dev/image_to_media_swapper.install
image_to_media_swapper.install
<?php
/**
* @file
* Install, update and uninstall functions for the module.
*/
/**
* Implements hook_install().
*/
function image_to_media_swapper_install(): void {
// Install the MediaSwapRecord entity schema.
$entity_update_manager = \Drupal::entityDefinitionUpdateManager();
// Check if the entity type is already installed.
if (!$entity_update_manager->getEntityType('media_swap_record')) {
$entity_type = \Drupal::entityTypeManager()->getDefinition('media_swap_record');
$entity_update_manager->installEntityType($entity_type);
}
}
/**
* Implements hook_uninstall().
*
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
function image_to_media_swapper_uninstall(): void {
// Remove the MediaSwapRecord entity schema.
$entity_update_manager = \Drupal::entityDefinitionUpdateManager();
if ($entity_update_manager->getEntityType('media_swap_record')) {
$entity_type_manager = \Drupal::entityTypeManager();
$entity_type = $entity_type_manager->getDefinition('media_swap_record');
$entity_update_manager->uninstallEntityType($entity_type);
}
}
/**
* Add new fields to MediaSwapRecord entity.
*/
function image_to_media_swapper_update_10001(): void {
$entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
// Get the current MediaSwapRecord entity type definition.
$entity_type = $entity_definition_update_manager->getEntityType('media_swap_record');
if (!$entity_type) {
$entity_update_manager = \Drupal::entityDefinitionUpdateManager();
$entity_type = \Drupal::entityTypeManager()->getDefinition('media_swap_record');
$entity_update_manager->installEntityType($entity_type);
}
// Get the storage definition for the new fields.
$field_storage_definitions = \Drupal::service('entity_field.manager')
->getFieldStorageDefinitions('media_swap_record');
// Install the new fields if they don't already exist.
$new_fields = ['source_file_id', 'created_media_id', 'conversion_details'];
foreach ($new_fields as $field_name) {
if (isset($field_storage_definitions[$field_name])) {
$field_definition = $field_storage_definitions[$field_name];
// Check if field already exists in the database.
$existing_definition = $entity_definition_update_manager->getFieldStorageDefinition($field_name, 'media_swap_record');
if (!$existing_definition) {
// Field doesn't exist in database, install it.
$entity_definition_update_manager->installFieldStorageDefinition($field_name, 'media_swap_record', 'image_to_media_swapper', $field_definition);
}
}
}
}
