You are here

function entity_usage_post_update_regenerate_3x in Entity Usage 8.3

Re-generate entity_usage statistics on the 3.x branch.

File

./entity_usage.post_update.php, line 16
Post-update hooks for entity_usage module.

Code

function entity_usage_post_update_regenerate_3x(&$sandbox) {

  // First pass.
  if (empty($sandbox['total'])) {
    $sandbox['current_key'] = 0;
    $sandbox['total'] = 0;
    $sandbox['entities'] = [];
    $top_level_types = EntityUsageSourceLevel::getTopLevelEntityTypes();
    $configured_to_track = \Drupal::config('entity_usage.settings')
      ->get('track_enabled_source_entity_types') ?: [];
    $to_track = array_intersect($top_level_types, $configured_to_track);
    foreach (\Drupal::entityTypeManager()
      ->getDefinitions() as $entity_type_id => $entity_type) {

      // Only look for entities enabled for tracking on the settings form.
      $track_this_entity_type = FALSE;
      if (!is_array($to_track) && $entity_type
        ->entityClassImplements('\\Drupal\\Core\\Entity\\ContentEntityInterface')) {

        // When no settings are defined, track all content entities by default,
        // except for Files and Users.
        if (!in_array($entity_type_id, [
          'file',
          'user',
        ])) {
          $track_this_entity_type = TRUE;
        }
      }
      elseif (is_array($to_track) && in_array($entity_type_id, $to_track, TRUE)) {
        $track_this_entity_type = TRUE;
      }
      if ($track_this_entity_type) {

        // Add all existing ids to be tracked again.
        $ids = \Drupal::entityQuery($entity_type_id)
          ->accessCheck(FALSE)
          ->execute();
        if (!empty($ids)) {
          $sandbox['total'] += count($ids);
          foreach ($ids as $id) {
            $sandbox['entities'][] = [
              'entity_type' => $entity_type_id,
              'entity_id' => $id,
            ];
          }
        }
      }
    }
  }

  // Abort the batch process if the site is big enough for this process to be
  // a very long-running process.
  $limit = Settings::get('entity_usage_3x_regenerate_limit', 2000);
  if ($sandbox['total'] > $limit) {
    $sandbox = [];
    return t('The automatic regeneration of usage statistics was skipped because it could potentially be very slow on this site. Make sure you visit the <a href="@batch_url">batch update</a> page and trigger the update manually.', [
      '@batch_url' => Url::fromRoute('entity_usage.batch_update')
        ->toString(),
    ]);
  }

  // Worker.
  $batch_size = 1;
  for ($i = $sandbox['current_key']; $i < $sandbox['current_key'] + $batch_size; $i++) {
    if (empty($sandbox['entities'][$i])) {
      break;
    }
    $entity_type = $sandbox['entities'][$i]['entity_type'];
    $entity_id = $sandbox['entities'][$i]['entity_id'];
    if ($entity_type && $entity_id) {
      $entity_storage = \Drupal::entityTypeManager()
        ->getStorage($entity_type);

      /** @var \Drupal\Core\Entity\EntityInterface $entity */
      $entity = $entity_storage
        ->load($entity_id);
      if ($entity && EntityUsageSourceLevel::isTopLevel($entity)) {
        if ($entity
          ->getEntityType()
          ->isRevisionable()) {

          // Track all revisions and translations of the source entity. Sources
          // are tracked as if they were new entities.
          $result = $entity_storage
            ->getQuery()
            ->allRevisions()
            ->condition($entity
            ->getEntityType()
            ->getKey('id'), $entity
            ->id())
            ->sort($entity
            ->getEntityType()
            ->getKey('revision'), 'DESC')
            ->execute();
          $revision_ids = array_keys($result);
          foreach ($revision_ids as $revision_id) {

            /** @var \Drupal\Core\Entity\EntityInterface $entity_revision */
            if (!($entity_revision = $entity_storage
              ->loadRevision($revision_id))) {
              continue;
            }
            \Drupal::service('entity_usage.entity_update_manager')
              ->recalculateUsageInformation($entity_revision);
          }
        }
        else {

          // Sources are tracked as if they were new entities.
          \Drupal::service('entity_usage.entity_update_manager')
            ->recalculateUsageInformation($entity);
        }
      }
    }
    $sandbox['current_key']++;
  }
  $sandbox['#finished'] = empty($sandbox['total']) ? 1 : $sandbox['current_key'] / $sandbox['total'];
  return t('Finished generating statistics for @total_count entities.', [
    '@total_count' => $sandbox['total'],
  ]);
}