Commit 0c801203 authored by Oleksandr Horbatiuk's avatar Oleksandr Horbatiuk 🧩 Committed by Fabian de Rijk
Browse files

Issue #3218736: Not enough memory for migrating accounts

parent c2339ee2
Loading
Loading
Loading
Loading
+52 −4
Original line number Diff line number Diff line
@@ -5,6 +5,8 @@
 * Install and update hooks for the o365_sso module.
 */

use Drupal\Core\Site\Settings;

/**
 * Implements hook_install().
 */
@@ -24,15 +26,61 @@ function o365_sso_update_9001() {
/**
 * Migrate existing accounts from 1.0.x to externalauth authmap
 */
function o365_sso_update_9002(){
function o365_sso_update_9002(&$sandbox){
  if (!isset($sandbox['total'])) {
    $sandbox['total'] = \Drupal::entityQuery('user')
      ->exists('o365_id')
      ->count()
      ->execute();

    $sandbox['cli'] = function_exists('drush_print');

    if (!$sandbox['total']) {
      $output = t('No accounts for migration.');

      if ($sandbox['cli']) {
        drush_print($output);
      }

      return $output;
    }

    $sandbox['last_id'] = $sandbox['processed'] = 0;
    $sandbox['limit'] = Settings::get('entity_update_batch_size', 500);
  }

  $authmap = \Drupal::service('externalauth.authmap');
  $users = \Drupal::entityTypeManager()->getStorage('user')->loadMultiple();

  foreach($users as $user) {
    if ($user->hasField('o365_id') && $o365_id = $user->o365_id->value){
  $user_ids = \Drupal::entityQuery('user')
    ->exists('o365_id')
    ->condition('uid', $sandbox['last_id'], '>')
    ->sort('uid')
    ->range(0, $sandbox['limit'])
    ->execute();

  $storage = \Drupal::entityTypeManager()->getStorage('user');

  foreach($user_ids as $user_id) {
    $user = $storage->load($user_id);
    if ($o365_id = $user->o365_id->value){
      $authmap->save($user, 'o365_sso', $o365_id);
    }
  }

  $sandbox['last_id'] = end($user_ids);
  $sandbox['processed'] += count($user_ids);

  if ($sandbox['processed'] < $sandbox['total']) {
    $sandbox['#finished'] = $sandbox['processed'] / $sandbox['total'];
  }

  $output = t('@count% of accounts have been migrated.', [
    '@count' => round(100 * $sandbox['processed'] / $sandbox['total']),
  ]);

  if ($sandbox['cli']) {
    drush_print($output);
  }

  return $output;
}