symfony7自定义command以及使用dry run
<?php
namespace App\Command;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(
name: 'update-publication-preference-descriptions',
description: 'Updates the description field in event_submission_publication_preferences to match the new names.',
)]
class UpdatePublicationPreferenceDescriptionsCommand extends Command
{
public function __construct(
private readonly EntityManagerInterface $em,
)
{
parent::__construct();
}
protected function configure(): void
{
$this
->addOption(
'dry-run',
null,
InputOption::VALUE_NONE,
'Preview the SQL updates without applying changes.'
);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$dryRun = $input->getOption('dry-run');
$updates = [
1 => "I do not want my abstract.",
2 => "I want my abstract to be published in the conference",
3 => "I would like to extend my abstract by submitting a full",
];
foreach ($updates as $typeId => $newDescription) {
if ($dryRun) {
$output->writeln(sprintf(
"[Dry Run] Would update description to:\n \"%s\"\n WHERE event_submission_publication_preference_type_id = %d\n",
$newDescription,
$typeId
));
} else {
$this->em->getConnection()->executeStatement(
'UPDATE event_submission_publication_preferences SET description = :description WHERE event_submission_publication_preference_type_id = :typeId',
[
'description' => $newDescription,
'typeId' => $typeId,
]
);
$output->writeln("Updated description for type_id $typeId.");
}
}
$output->writeln($dryRun ? 'Dry run complete.' : 'All descriptions updated successfully.');
return Command::SUCCESS;
}
}
