Repository URL to install this package:
|
Version:
2.2.0 ▾
|
<?php
namespace MeltConsole\App\Commands;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\ConfirmationQuestion;
/**
* Class to deploy code.
*/
class BackupRemoteDatabaseCommand extends MeltCommand {
/**
* Question helper.
*
* @var \Symfony\Component\Console\Helper\QuestionHelper
*/
private $question;
/**
* {@inheritdoc}
*/
protected function configure() {
// Initial config for command.
$this
->setName('melt:backup-remote-database')
->setAliases(['melt:brd'])
->setDescription('Creates backup on remote environment')
->setHelp('Creates backup to backup directory.')
->addOption('env', 'e', InputOption::VALUE_REQUIRED, 'Environment e.g dev, qa, stage');
}
/**
* {@inheritdoc}
*/
protected function interact(InputInterface $input, OutputInterface $output) {
// TODO: Change the autogenerated stub.
parent::interact($input, $output);
$this->question = $this->getHelper('question');
if (!$input->getOption('env')) {
// Ask the user some stuff.
$envs = $this->getEnvironmentsFromServer();
$question = new ChoiceQuestion('Choose environment to backup: ', $envs);
if (empty($envs)) {
throw new \Exception('There are currently no environments.');
}
$env = $this->question->ask($input, $output, $question);
// Set options based on users answer.
$input->setOption('env', $env);
}
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output) {
$env = $input->getOption('env');
if (!$this->validateEnvironmentExistsOnServer($env)) {
throw new \Exception('Environment doesn\'t exist.');
}
$output->write("Creating backup on the server...");
$backupPath = $this->backupRemoteDatabase($env);
$output->write("Backup created at <info>{$backupPath}</info> on the server.");
}
/**
* Backs up remote database.
*
* @param string $env
* Environment.
*/
protected function backupRemoteDatabase(string $env) {
// Year month day hour minute.
$timestamp = date('Ymdhi');
$envDir = "{$this->projectName}-{$env}";
$backupName = "{$envDir}-backup-{$timestamp}.sql";
$backupDir = '/opt/backups';
$this->runServerCommands([
"cd /{$this->serverRoot}/{$envDir}",
"mkdir -p backups",
"drush sql:dump --gzip --result-file={$backupDir}/{$backupName}",
]);
return "{$backupDir}/{$backupName}.gz";
}
}