You are here

function og_update_8001 in Organic groups 8

Add a base field to store the group bundle in memberships.

File

./og.install, line 24

Code

function og_update_8001(&$sandbox) {
  $storage = \Drupal::entityTypeManager()
    ->getStorage('og_membership');
  if (!isset($sandbox['total'])) {
    $storage_definition = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Group bundle ID'))
      ->setDescription(new TranslatableMarkup('The bundle ID of the group.'));
    \Drupal::entityDefinitionUpdateManager()
      ->installFieldStorageDefinition('entity_bundle', 'og_membership', 'og', $storage_definition);
    $sandbox['#finished'] = 0;
    $sandbox['batch_size'] = 500;
    $sandbox['current'] = 0;
    $sandbox['total'] = $storage
      ->getQuery()
      ->count()
      ->execute();
    if (!$sandbox['total']) {
      $sandbox['#finished'] = 1;
      return new TranslatableMarkup('No OG memberships found.');
    }
  }

  // Update the existing memberships to include the group bundle ID.
  $membership_ids = $storage
    ->getQuery()
    ->range($sandbox['current'], $sandbox['batch_size'])
    ->sort('id')
    ->execute();

  /** @var \Drupal\og\Entity\OgMembership $membership */
  foreach ($storage
    ->loadMultiple($membership_ids) as $membership) {
    $group = $membership
      ->getGroup();
    if (!empty($group)) {
      $membership
        ->set('entity_bundle', $group
        ->bundle());
      $membership
        ->save();
    }
    else {

      // The membership is for a group that no longer exists. We cannot no
      // longer retrieve the group bundle ID so the membership cannot be
      // updated. Delete the membership since it is invalid, and inform the
      // user.
      \Drupal::logger('og')
        ->warning('Deleted orphaned membership with ID @id since the group it refers to no longer exists.', [
        '@id' => $membership
          ->id(),
      ]);
      $membership
        ->delete();
    }
  }
  $sandbox['current'] += $sandbox['batch_size'];
  if ($sandbox['current'] >= $sandbox['total']) {
    $sandbox['current'] = $sandbox['total'];
  }
  $sandbox['#finished'] = $sandbox['current'] / $sandbox['total'];
  $message = new TranslatableMarkup('Processed @current of @total memberships (@percentage% complete)', [
    '@current' => $sandbox['current'],
    '@total' => $sandbox['total'],
    '@percentage' => number_format($sandbox['#finished'] * 100, 2),
  ]);
  return $message;
}