You are here

public static function BatchUpdateForm::updateHostsBatchWorker in Entity Usage 8

Batch operation worker for recreating statistics for host entities.

Parameters

string $entity_type_id: The entity type id, for example 'node'.

array $context: The context array.

File

src/Form/BatchUpdateForm.php, line 137

Class

BatchUpdateForm
Form to launch batch tracking of existing entities.

Namespace

Drupal\entity_usage\Form

Code

public static function updateHostsBatchWorker($entity_type_id, array &$context) {
  $entity_storage = \Drupal::entityTypeManager()
    ->getStorage($entity_type_id);
  $entity_type = \Drupal::entityTypeManager()
    ->getDefinition($entity_type_id);
  $entity_type_key = $entity_type
    ->getKey('id');
  if (empty($context['sandbox']['total'])) {

    // Delete current usage statistics for these entities.
    \Drupal::service('entity_usage.usage')
      ->bulkDeleteHosts($entity_type_id);
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_id'] = -1;
    $context['sandbox']['total'] = (int) $entity_storage
      ->getQuery()
      ->accessCheck(FALSE)
      ->count()
      ->execute();
  }
  $entity_ids = $entity_storage
    ->getQuery()
    ->condition($entity_type_key, $context['sandbox']['current_id'], '>')
    ->range(0, 10)
    ->accessCheck(FALSE)
    ->sort($entity_type_key)
    ->execute();
  $entities = $entity_storage
    ->loadMultiple($entity_ids);
  foreach ($entities as $entity) {

    // Hosts are tracked as if they were new entities.
    \Drupal::service('entity_usage.entity_update_manager')
      ->trackUpdateOnCreation($entity);
    $context['sandbox']['progress']++;
    $context['sandbox']['current_id'] = $entity
      ->id();
    $context['results'][] = $entity_type_id . ':' . $entity
      ->id();
  }
  if ($context['sandbox']['progress'] < $context['sandbox']['total']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['total'];
  }
  else {
    $context['finished'] = 1;
  }
  $context['message'] = t('Updating entity usage for @entity_type: @current of @total', [
    '@entity_type' => $entity_type_id,
    '@current' => $context['sandbox']['progress'],
    '@total' => $context['sandbox']['total'],
  ]);
}