You are here

function contact_emails_update_8005 in Contact Emails 8

Migrate the contact emails table to the contact emails entity table.

File

./contact_emails.install, line 165
Contact emails database table.

Code

function contact_emails_update_8005(&$sandbox) {
  $connection = \Drupal::database();

  // Ensure the new entity type is installed on update. It is installed
  // automatically on a fresh install.
  $entity_manager = \Drupal::entityTypeManager();
  $update_manager = \Drupal::entityDefinitionUpdateManager();
  $entity_manager
    ->clearCachedDefinitions();
  if ($definition = $entity_manager
    ->getDefinition('contact_email')) {
    $update_manager
      ->installEntityType($definition);
  }
  if ($connection
    ->schema()
    ->tableExists('contact_message_email_settings')) {

    // Initialize the batch update.
    if (!isset($sandbox['progress'])) {

      // This must be the first run. Initialize the sandbox.
      $sandbox['progress'] = 0;
      $sandbox['current_id'] = 0;
      $sandbox['max'] = $connection
        ->select('contact_message_email_settings')
        ->countQuery()
        ->execute()
        ->fetchField();
    }
    if ($sandbox['max']) {

      // Update in chunks of 10.
      $records = $connection
        ->select('contact_message_email_settings', 'm')
        ->fields('m')
        ->condition('m.id', $sandbox['current_id'], '>')
        ->range(0, 10)
        ->orderBy('m.id', 'ASC')
        ->execute()
        ->fetchAll();
      if ($records) {
        foreach ($records as $record) {

          // Create a new email.
          $data = (array) $record;
          unset($data['id']);
          $data['status'] = (bool) (!$data['disabled']);
          $data['message'] = isset($data['message']) ? $data['message'] : $data['body'];
          unset($data['disabled']);
          $contact_email = ContactEmail::create($data);
          $contact_email
            ->save();
          $sandbox['progress']++;
          $sandbox['current_id'] = $record->id;
        }
      }
      $sandbox['#finished'] = empty($sandbox['max']) ? 1 : $sandbox['progress'] / $sandbox['max'];
    }
    else {
      $sandbox['#finished'] = 1;
    }

    // Delete the database table.
    $connection
      ->delete('contact_message_email_settings');
    return t('All emails have been successfully updated to translatable entities.');
  }
}