Namespace
Drupal\devel_generate\Command
File
-
devel_generate/src/Command/GenerateCommandTrait.php
View source
<?php
declare (strict_types=1);
namespace Drupal\devel_generate\Command;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Routing\RouteObjectInterface;
use Drupal\devel_generate\DevelGeneratePluginManager;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Route;
trait GenerateCommandTrait {
public function __construct(protected readonly DevelGeneratePluginManager $manager, protected readonly ModuleHandlerInterface $moduleHandler, protected readonly MessengerInterface $messenger, protected readonly RequestStack $requestStack) {
}
protected function generate(string $plugin_id, InputInterface $input, OutputInterface $output, array $modules = []) : int {
$missing = array_filter($modules, fn(string $module): bool => !$this->moduleHandler
->moduleExists($module));
if ($missing !== []) {
throw new \RuntimeException(sprintf('Install these modules first: %s', implode(', ', $missing)));
}
$instance = $this->manager
->createInstance($plugin_id, []);
try {
$parameters = $instance->validateDrushParams($input->getArguments(), $input->getOptions());
$instance->generate($parameters);
$this->processBatch();
} finally {
$this->writeMessages($input, $output);
}
return Command::SUCCESS;
}
protected function processBatch() : void {
$batch =& batch_get();
if (empty($batch)) {
return;
}
$batch['progressive'] = FALSE;
$request = $this->requestStack
->getCurrentRequest();
if ($request && !$request->attributes
->has(RouteObjectInterface::ROUTE_OBJECT)) {
$request->attributes
->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
$request->attributes
->set(RouteObjectInterface::ROUTE_NAME, '<none>');
}
batch_process();
}
protected function writeMessages(InputInterface $input, OutputInterface $output) : void {
$io = (new SymfonyStyle($input, $output))->getErrorStyle();
foreach ($this->messenger
->deleteAll() as $type => $messages) {
foreach ($messages as $message) {
$message = trim(html_entity_decode(strip_tags((string) $message), ENT_QUOTES | ENT_HTML5));
match ($type) { MessengerInterface::TYPE_ERROR => $io->error($message),
MessengerInterface::TYPE_WARNING => $io->warning($message),
default => $io->writeln($message),
};
}
}
}
}
Traits