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;
use Symfony\Component\Console\Exception\LogicException;
/**
* Class to push database.
*/
class PushDatabaseCommand extends MeltCommand {
/**
* Question helper.
*
* @var \Symfony\Component\Console\Helper\QuestionHelper
*/
private $question;
/**
* {@inheritdoc}
*/
protected function configure() {
// Initial config for command.
$this
->setName('melt:push-database')
->setAliases(['melt:pushd'])
->setDescription('Push database to remote environment.')
->setHelp('Pushes local database to remote environment.')
->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 push to: ', $envs);
if (empty($envs)) {
throw new LogicException('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.');
}
// Year month day hour minute.
$timestamp = date('Ymdhi');
$srcDir = "{$this->projectName}.local";
$destDir = "{$this->projectName}.{$env}";
$drushAlias = "@melt.{$env}";
$localBackupName = "{$srcDir}-backup-{$timestamp}.sql.gz";
$serverBackupName = "{$destDir}-backup-{$timestamp}.sql";
$output->writeln("Pushing database in progress...");
$this->runLocalCommands([
"drush sql:dump --gzip --result-file=../{$localBackup}",
"drush rsync @self:../{$localLandoBackup} {$drushAlias}:{$localBackup}",
]);
// Should we auto-import the database for them?
$question = new ConfirmationQuestion('Would you like to import the database? (n/Y)');
if ($this->question->ask($input, $output, $question)) {
$this->runServerCommands([
"cd {$this->serverRoot}/{$destDir}",
// Create backups directory if it doesn't already exist.
"mkdir -p backups",
// Create backup of current database just in case we need to restore.
"lando db-export backups/{$serverBackupName}",
// Import database from local environment.
"lando db-import {$localBackup}",
// Remove local import file.
"rm -f {$localBackup}",
]);
}
$output->writeln('<info>Done!</info>');
}
}