devel_wizard-2.x-dev/src/Commands/SpellCommandsBase.php
src/Commands/SpellCommandsBase.php
<?php
declare(strict_types=1);
namespace Drupal\devel_wizard\Commands;
use Drupal\Component\Plugin\ConfigurableInterface;
use Drupal\devel_wizard\Spell\SpellAbracadabraBatchHandler;
use Drupal\devel_wizard\Spell\SpellManagerInterface;
use Drush\Attributes as CLI;
use Drush\Commands\DrushCommands;
use Psr\Log\LoggerAwareInterface;
use ReflectionException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\String\UnicodeString;
abstract class SpellCommandsBase extends DrushCommands {
protected SpellManagerInterface $spellManager;
public function __construct(SpellManagerInterface $spellManager) {
$this->spellManager = $spellManager;
parent::__construct();
}
/**
* @hook option
*/
public function onHookOption(Command $command) {
$spellId = $this->getSpellIdFromCommandName($command->getName());
/* @noinspection PhpUnhandledExceptionInspection */
$spell = $this->spellManager->createInstance($spellId);
if (!$command->getHelp()) {
$command->setHelp((string) $spell->getPluginDefinition()->getDescription());
}
if (!$command->getDescription()) {
$command->setDescription((string) $spell->getPluginDefinition()->getDescription());
}
}
protected function execute(): void {
$spellId = $this->getSpellIdFromInput();
/* @noinspection PhpUnhandledExceptionInspection */
$spell = $this->spellManager->createInstance($spellId);
$spellConfiguration = $this->buildSpellConfigurationFromInput();
if ($spell instanceof ConfigurableInterface) {
$spell->setConfiguration($spellConfiguration);
}
if ($spell instanceof LoggerAwareInterface) {
$spell->setLogger($this->logger());
}
$batchBuilder = SpellAbracadabraBatchHandler::build($spell);
batch_set($batchBuilder->toArray());
drush_backend_batch_process();
}
protected function getSpellIdFromInput(): string {
$commandName = $this->input()->getArgument('command');
return $this->getSpellIdFromCommandName($commandName);
}
protected function getSpellIdFromCommandName(string $commandName): string {
return (new UnicodeString($commandName))
->trimPrefix('devel-wizard:spell:')
->replace(':', '_')
->replace('-', '_')
->toString();
}
abstract protected function buildSpellConfigurationFromInput(): array;
protected function getCommandInputDescription(string $methodName, string $inputType, string $inputName): ?string {
$reflection = new \ReflectionClass($this);
try {
$method = $reflection->getMethod($methodName);
}
catch (ReflectionException $e) {
assert(FALSE, $e->getMessage());
}
$inputAttributeClass = $inputType === 'argument' ?
CLI\Argument::class
: CLI\Option::class;
$attributes = $method?->getAttributes($inputAttributeClass) ?: [];
foreach ($attributes as $attribute) {
/** @var \Drush\Attributes\Argument|\Drush\Attributes\Option $attr */
$attr = $attribute->newInstance();
if ($attr->name === $inputName) {
return $attr->description;
}
}
return NULL;
}
}
