devel_wizard-2.x-dev/src/Spell/SpellAbracadabraBatchHandler.php
src/Spell/SpellAbracadabraBatchHandler.php
<?php
declare(strict_types=1);
namespace Drupal\devel_wizard\Spell;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Batch\BatchBuilder;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class SpellAbracadabraBatchHandler implements ContainerInjectionInterface {
use StringTranslationTrait;
protected SpellManagerInterface $spellManager;
protected MessengerInterface $messenger;
public static function build(SpellInterface $spell): BatchBuilder {
$spellConfiguration = $spell->getConfiguration();
$batchBuilder = new BatchBuilder();
$batchBuilder
->setTitle($spell->getPluginDefinition()->getLabel())
->setFinishCallback([static::class, 'finish'])
->addOperation(
[static::class, 'process'],
[
$spell->getPluginDefinition()->id(),
$spellConfiguration,
],
);
return $batchBuilder;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('string_translation'),
$container->get('messenger'),
$container->get('plugin.manager.devel_wizard.spell'),
);
}
public function __construct(
TranslationInterface $stringTranslation,
MessengerInterface $messenger,
SpellManagerInterface $spellManager,
) {
$this->setStringTranslation($stringTranslation);
$this->messenger = $messenger;
$this->spellManager = $spellManager;
}
/**
* @see \DrushBatchContext
*/
public static function process(string $spellId, array $configuration, array|\ArrayObject &$context): void {
$handler = static::create(\Drupal::getContainer());
$handler->doProcess($spellId, $configuration, $context);
}
public static function finish(bool $success, array $results, array $operations): void {
$handler = static::create(\Drupal::getContainer());
$handler->doFinish($success, $results, $operations);
}
protected function doProcess(string $spellId, array $configuration, array|\ArrayObject &$context): void {
try {
$spell = $this->spellManager->createInstance($spellId, $configuration);
}
catch (PluginException $exception) {
$context['results']['messages'][] = [
'type' => MessengerInterface::TYPE_ERROR,
'message' => $exception->getMessage(),
];
$context['finished'] = 1.0;
return;
}
$spell->prepare();
$spell->abracadabra($context);
}
/**
* @link https://www.drupal.org/project/drupal/issues/604902#comment-4197954
*/
protected function doFinish(bool $success, array $results, array $operations): void {
if (!$success) {
$this->messenger->addError($this->t('Spell failed'));
}
foreach ($results['messages'] ?? [] as $msg) {
$this->messenger->addMessage($msg['message'], $msg['type']);
}
}
}
