dbmanager/src/Console/CreateUserCommand.php

62 lines
2.1 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\ConfirmationQuestion;
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('user', 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');
$user = $input->getArgument('user');
$password = $input->getArgument('password');
$host = $input->getArgument('host');
if (!$user) {
$user = $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($user, $password, $host);
$output->writeln(sprintf('User "%s" successfully created', $user));
// ask to create a database for the user
$createDbQuestion = new ConfirmationQuestion('Create a database for this user?', false);
if ($question->ask($input, $output, $createDbQuestion)) {
$this->db->createDatabase($user);
$this->db->grantDatabaseAdminPermission($user, $user, $host);
$output->writeln(sprintf('Database "%s" successfully created and granted to "%s"', $user, $user));
}
return Command::SUCCESS;
}
}