Skip to content

Instantly share code, notes, and snippets.

@colorfield
Last active April 18, 2016 16:21
Show Gist options
  • Save colorfield/d9b5ab183c6c246786935871307227a7 to your computer and use it in GitHub Desktop.
Save colorfield/d9b5ab183c6c246786935871307227a7 to your computer and use it in GitHub Desktop.
Drupal 8 batch opertation
<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
class BatchProcessController extends ControllerBase
{
const OPERATION_CREATE = 0;
const OPERATION_UPDATE = 1;
const OPERATION_DELETE = 2;
/**
* Finish batch.
*/
public static function finishBatch($success, $results, $operations)
{
// @todo we can use here the $results for displaying further information
if ($success) {
if (!empty($results['errors'])) {
foreach ($results['errors'] as $error) {
drupal_set_message($error, 'error');
\Drupal::logger('json_migrate')->error($error);
}
drupal_set_message(\Drupal::translation()
->translate('The content was imported with errors.'), 'warning');
}
else {
drupal_set_message(\Drupal::translation()
->translate('The content was imported successfully.'));
}
}
else {
// An error occurred.
// $operations contains the operations that remained unprocessed.
$error_operation = reset($operations);
$message = \Drupal::translation()
->translate('An error occurred while processing %error_operation with arguments: @arguments', array(
'%error_operation' => $error_operation[0],
'@arguments' => print_r($error_operation[1], TRUE)
));
drupal_set_message($message, 'error');
}
}
/**
* Merely displays a message, should be used for other purpose.
* @return array
*/
public function getResults()
{
return array(
'#type' => 'markup',
'#markup' => $this->t('Batch process finished'),
);
}
/**
* Processes the batch.
*
* @param int $amount
* Count of the contents.
* @param int $operation
* Current operation to run the batch on.
* @param string $content
* The content to import.
* @param array $context
* The batch context.
*/
public static function processBatch($amount, $operation, $content, &$context)
{
//@todo process here the heavy work on the content
// cannot use dependency injection an need static call from a static context
\Drupal::logger('json_migrate')->info(
\Drupal::translation()
->translate('Imported content %content', array('%content' => $content))
);
// review e.g. \Drupal\migrate_drupal_ui\MigrateUpgradeRunBatch
// if (!isset($context['sandbox']['current'])) {
// $context['sandbox']['current_id'] = $content->id; // @todo get id, e.g. nid
// $context['sandbox']['max'] = $amount;
// $context['sandbox']['num_processed'] = 0;
// $context['sandbox']['messages'] = [];
// $context['results']['failures'] = 0;
// $context['results']['successes'] = 0;
// $context['results']['operation'] = $operation;
// }
// else {
// $context['sandbox']['current_id'] = $content->id; // @todo get id, e.g. nid
// $context['sandbox']['num_processed']++;
// $context['results']['failures'] = 0; // @todo fetched from the result
// $context['sandbox']['messages'][] = ''; // @todo optional message
// $context['results']['successes']++; // @todo fetched from the result
// }
// Store some result for post-processing in the finished callback.
// $context['results'][] = $content;
// $context['message'] = t('Now processing %node', array('%node' => $content));
// if ($errors = $myWorkerClass->getErrors()) {
// if (!isset($context['results']['errors'])) {
// $context['results']['errors'] = array();
// }
// $context['results']['errors'] += $errors;
// }
}
public function initBatch()
{
try {
// a list of contents to process
$contentToMigrate = array(
1,
2,
3,
4,
5
);
$batch = [
'operations' => [],
'finished' => [BatchFinishController::class, 'finishBatch'],
'title' => $this->t('Migrating content'),
'init_message' => $this->t('Starting content migration.'),
'progress_message' => $this->t('Completed @current step of @total.'),
'error_message' => $this->t('Content migration has encountered an error.'),
];
$amount = count($contentToMigrate);
$operation = BatchProcessController::OPERATION_CREATE;
foreach ($contentToMigrate as $content) {
$batch['operations'][] = [
[get_class($this), 'processBatch'],
[$amount, $operation, $content]
];
}
batch_set($batch);
} // @todo custom exception
catch (\Exception $e) {
drupal_set_message($e->getMessage(), 'error');
}
$url = Url::fromRoute('json_migrate.batch_finish');
return batch_process($url);
}
}
my_module.batch_process:
path: '/admin/my_module/batch/process'
defaults:
_controller: '\Drupal\my_module\Controller\BatchController::initBatch'
_title: 'Batch init'
requirements:
_permission: 'administer site configuration'
my_module.batch_finish:
path: '/admin/my_module/batch/finish'
defaults:
_controller: '\Drupal\my_module\Controller\BatchController::getResults'
_title: 'Batch results'
requirements:
_permission: 'administer site configuration'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment