Skip to content

Instantly share code, notes, and snippets.

@matteocaberlotto
Created February 13, 2023 11:10
Show Gist options
  • Save matteocaberlotto/c075a106e8a7418b9fa24ffaf5322e95 to your computer and use it in GitHub Desktop.
Save matteocaberlotto/c075a106e8a7418b9fa24ffaf5322e95 to your computer and use it in GitHub Desktop.
Basic Symfony command for password update
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\DependencyInjection\ContainerInterface;
use App\Entity\User;
class UpdateUserPasswordCommand extends Command
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct();
}
protected function configure()
{
$this
->setName('update:user:password')
->setDescription('Update user password')
->addArgument('email', InputArgument::REQUIRED)
->addArgument('password', InputArgument::REQUIRED)
;
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$doctrine = $this->container->get('doctrine');
$manager = $doctrine->getManager();
$user = $doctrine->getRepository(User::class)->findOneBy([
'email' => $input->getArgument('email'),
]);
if (!$user) {
$output->writeln("<error>User not found</error>");
return;
}
$user->setPlainPassword($input->getArgument('password'));
$this->container->get('password.updater')->hashPassword($user);
$manager->flush();
$output->writeln("Password for " . $user . " updated.");
return 0;
}
/**
* {@inheritdoc}
*/
protected function interact(InputInterface $input, OutputInterface $output)
{
if (!$input->getArgument('email')) {
$question = new Question('Please enter user email:');
$question->setValidator(function ($password) {
if (empty($password)) {
throw new \Exception('Email can not be empty');
}
return $password;
});
$questions['email'] = $question;
}
if (!$input->getArgument('password')) {
$question = new Question('Please enter the new password:');
$question->setValidator(function ($password) {
if (empty($password)) {
throw new \Exception('Password can not be empty');
}
return $password;
});
$question->setHidden(true);
$questions['password'] = $question;
}
foreach ($questions as $name => $question) {
$answer = $this->getHelper('question')->ask($input, $output, $question);
$input->setArgument($name, $answer);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment