You are here

function preview_link_update_8205 in Preview Link 2.x

Same name and namespace in other branches
  1. 2.0.x preview_link.install \preview_link_update_8205()

Migrates entity relationship data to new field.

File

./preview_link.install, line 97
Install file.

Code

function preview_link_update_8205(array &$sandbox) : TranslatableMarkup {

  // Bail out early if the entity type is not using the default storage class.
  $storage = \Drupal::entityTypeManager()
    ->getStorage('preview_link');
  if (!$storage instanceof PreviewLinkStorageInterface) {
    return \t('The entity type is not using the default storage class.');
  }
  $tableMapping = $storage
    ->getTableMapping();
  $step_size = Settings::get('entity_update_batch_size', 50);
  if (!isset($sandbox['current_id'])) {

    // This must be the first run. Initialize the sandbox.
    $sandbox['progress'] = 0;
    $sandbox['current_id'] = 0;
  }
  $database = \Drupal::database();
  $previewLinks = $database
    ->select($tableMapping
    ->getBaseTable(), 'pl')
    ->condition('pl.id', $sandbox['current_id'], '>')
    ->fields('pl')
    ->orderBy('id', 'ASC')
    ->range(0, $step_size)
    ->execute()
    ->fetchAll();
  if ($previewLinks) {
    $insert = $database
      ->insert($tableMapping
      ->getFieldTableName('entities'));
    $insert
      ->fields([
      'bundle',
      'deleted',
      'entity_id',
      'revision_id',
      'langcode',
      'delta',
      'entities_target_id',
      'entities_target_type',
    ]);
    foreach ($previewLinks as $previewLink) {
      $sandbox['current_id'] = $previewLink->id;
      $values = [
        'bundle' => 'preview_link',
        'deleted' => 0,
        'entity_id' => $previewLink->id,
        'revision_id' => $previewLink->id,
        'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
        'delta' => 0,
        'entities_target_type' => $previewLink->entity_type_id,
        'entities_target_id' => $previewLink->entity_id,
      ];
      $insert
        ->values($values);
    }
    $insert
      ->execute();
    $sandbox['progress'] += count($previewLinks);

    // If we're not in maintenance mode, the number of preview link could change
    // at any time so make sure that we always use the latest record count.
    $count = $database
      ->select($tableMapping
      ->getBaseTable(), 'pl')
      ->condition('pl.id', $sandbox['current_id'], '>')
      ->orderBy('id', 'ASC')
      ->countQuery()
      ->execute()
      ->fetchField();
    $sandbox['#finished'] = $count ? $sandbox['progress'] / ($sandbox['progress'] + (int) $count) : 1;
  }
  else {
    $sandbox['#finished'] = 1;
  }
  if ($sandbox['#finished'] >= 1) {
    return \t('Migrates entity relationship data to new field for preview link.');
  }
  return \t('Finished migrating relationship data to new field.');
}