dbmanager/src/Console/RestoreDatabaseCommand.php

61 lines
1.9 KiB
PHP

<?php
namespace App\Console;
use App\Service\BackupService;
use App\Service\DatabaseService;
use App\Service\Traits\SelectDatabaseQuestion;
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\ChoiceQuestion;
use Symfony\Component\Finder\Finder;
#[AsCommand('db:restore')]
class RestoreDatabaseCommand extends Command
{
use SelectDatabaseQuestion;
public function __construct(
private readonly DatabaseService $db,
private readonly BackupService $bs,
)
{
parent::__construct();
}
protected function configure(): void
{
$this->addArgument('name', InputArgument::OPTIONAL, 'Database name');
$this->addArgument('file', InputArgument::OPTIONAL, 'Backup file name');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$db = $this->getDatabaseName($input, $output);
$fileName = $input->getArgument('file');
if (!$fileName){
$fileName = $this->getFileName($input, $output);
}
$this->bs->restore($db, $fileName);
return Command::SUCCESS;
}
private function getFileName(InputInterface $input, OutputInterface $output): string
{
$finder = new Finder();
$finder->in(__DIR__ . '/../..');
$files = [];
foreach ($finder->files()->name('*_backup.sql') as $file) {
$files[] = $file->getFilename();
}
sort($files);
$selectQuestion = new ChoiceQuestion('Backup name (*_backup.sql): ', $files);
$question = $this->getHelper('question');
return $question->ask($input, $output, $selectQuestion);
}
}