dbmanager/src/Console/CreateUserCommand.php

53 lines
1.6 KiB
PHP

<?php
namespace App\Console;
use App\Service\DatabaseService;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
#[AsCommand('app:user:create')]
class CreateUserCommand extends Command
{
public function __construct(
private readonly DatabaseService $db,
)
{
parent::__construct();
}
public function configure(): void
{
$this->addArgument('name', InputArgument::OPTIONAL, 'User name');
$this->addArgument('password', InputArgument::OPTIONAL, 'User password');
$this->addArgument('host', InputArgument::OPTIONAL, 'User host');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$question = $this->getHelper('question');
$name = $input->getArgument('name');
$password = $input->getArgument('password');
$host = $input->getArgument('host');
if (!$name) {
$name = $question->ask($input, $output, new Question('User name: '));
}
if (!$password) {
$passwordQuestion = new Question('User password: ');
$passwordQuestion->setHidden(true);
$password = $question->ask($input, $output, $passwordQuestion);
}
$this->db->createUser($name, $password, $host);
$output->writeln(sprintf('User "%s" successfully created', $name));
return Command::SUCCESS;
}
}