LayoutBuilderBlockSanitizerBatch.php in Layout Builder Block Sanitizer 8
File
src/LayoutBuilderBlockSanitizerBatch.php
View source
<?php
namespace Drupal\layout_builder_block_sanitizer;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LayoutBuilderBlockSanitizerBatch implements ContainerInjectionInterface {
use StringTranslationTrait;
protected $layoutBuilderBlockSanitizerManager;
protected $layoutBuilderBlockSanitizerBatch;
public function __construct(LayoutBuilderBlockSanitizerManager $layout_builder_block_sanitizer_manager) {
$this->layoutBuilderBlockSanitizerManager = $layout_builder_block_sanitizer_manager;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('layout_builder_block_sanitizer.manager'));
}
public function batchSanitizeAllNodesStart() {
$nodes = $this->layoutBuilderBlockSanitizerManager
->getNodes();
$nids = array_keys($nodes);
batch_set([
'title' => $this
->t('Sanitizing nodes'),
'init_message' => $this
->t('Beginning node sanitize'),
'operations' => [
[
[
'Drupal\\layout_builder_block_sanitizer\\LayoutBuilderBlockSanitizerBatch',
'batchSanitizeAllNodes',
],
[
$nids,
],
],
],
'finished' => [
'Drupal\\layout_builder_block_sanitizer\\LayoutBuilderBlockSanitizerBatch',
'batchCompleted',
],
]);
}
public static function batchSanitizeAllNodes($nids, &$context) {
if (empty($context['sandbox'])) {
drupal_flush_all_caches();
$context['sandbox'] = [];
$context['sandbox']['progress'] = 0;
$context['sandbox']['current_node'] = 0;
$context['sandbox']['max'] = count($nids);
}
$limit = 5;
$current_node = $context['sandbox']['current_node'];
$limit_node = $context['sandbox']['current_node'] + $limit;
$result = range($current_node, $limit_node);
foreach ($result as $row) {
\Drupal::service('layout_builder_block_sanitizer.manager')
->sanitizeNode($nids[$row]);
$operation_details = t('Sanitizing NIDs :current to :limit', [
':current' => $current_node,
':limit' => $limit_node,
]);
$context['results'][] = $row;
$context['sandbox']['progress']++;
$context['sandbox']['current_node'] = $row;
$context['message'] = t('@details', [
'@details' => $operation_details,
]);
}
if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
$context['finished'] = $context['sandbox']['progress'] >= $context['sandbox']['max'];
}
}
public static function batchCompleted($success, $results, $operations) {
$messenger = \Drupal::messenger();
if ($success == TRUE) {
$messenger
->addMessage(t('@count nodes were sanitized.', [
'@count' => count($results),
]));
}
else {
$messenger
->addMessage(t('An error occurred while processing.'));
}
}
}