You are here

public function NodeRevisionsAutocleanCommands::deleteRevisionsAccordingSiteSettingsBatch in Node Revisions Autoclean 8

Deletes old revisions according to site's settings - batch.

@command nra-delete-old-revisions-batch @validate-module-enabled node @aliases nra:dorb

File

src/Commands/NodeRevisionsAutocleanCommands.php, line 85

Class

NodeRevisionsAutocleanCommands
Class NodeRevisionsAutocleanCommands.

Namespace

Drupal\node_revisions_autoclean\Commands

Code

public function deleteRevisionsAccordingSiteSettingsBatch() {
  $this
    ->logger()
    ->info('Revision deletion batch operations start');
  try {
    $storage = $this->entityTypeManager
      ->getStorage('node');
    $query = $storage
      ->getQuery()
      ->condition('status', '1');
    $nids = $query
      ->execute();
  } catch (\Exception $e) {
    $this
      ->logger()
      ->error($e
      ->getMessage());
  }
  $operations = [];
  $numOperations = 0;
  $batchId = 1;

  // Defining the batch builder.
  $batch_builder = new BatchBuilder();
  $batch_builder
    ->setFinishCallback([
    Batch::class,
    'processNodeFinished',
  ]);
  if (!empty($nids)) {
    foreach ($nids as $nid) {
      $this
        ->logger()
        ->info($this
        ->t("Preparing batch : @id ", [
        '@id' => $batchId,
      ]));

      // Adding the operation.
      $batch_builder
        ->addOperation([
        Batch::class,
        'processNode',
      ], [
        $batchId,
        $nid,
      ]);
      $batchId++;
      $numOperations++;
    }
  }
  else {
    $this
      ->logger()
      ->warning('No nodes');
  }

  // Setting the title.
  $batch_builder
    ->setTitle($this
    ->t('Node revisions autoclean  @num node(s)', [
    '@num' => $numOperations,
  ]));

  // Setting the batch.
  batch_set($batch_builder
    ->toArray());
  drush_backend_batch_process();
  $this
    ->logger()
    ->info("Batch operations end.");
}