1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Rougin\Refinery\Commands; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\Console\Input\InputArgument; |
6
|
|
|
use Symfony\Component\Console\Input\InputInterface; |
7
|
|
|
use Symfony\Component\Console\Output\OutputInterface; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Rollback Command |
11
|
|
|
* |
12
|
|
|
* Returns to a previous or specified migration. |
13
|
|
|
* |
14
|
|
|
* @package Refinery |
15
|
|
|
* @author Rougin Royce Gutib <[email protected]> |
16
|
|
|
*/ |
17
|
|
|
class RollbackCommand extends AbstractCommand |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* Sets the configurations of the specified command. |
21
|
|
|
* |
22
|
|
|
* @return void |
23
|
|
|
*/ |
24
|
33 |
|
protected function configure() |
25
|
|
|
{ |
26
|
33 |
|
$this->setName('rollback') |
27
|
33 |
|
->setDescription('Returns to a previous or specified migration') |
28
|
33 |
|
->addArgument('version', InputArgument::OPTIONAL, 'Specified version of the migration'); |
29
|
33 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Executes the command. |
33
|
|
|
* |
34
|
|
|
* @param \Symfony\Component\Console\Input\InputInterface $input |
35
|
|
|
* @param \Symfony\Component\Console\Output\OutputInterface $output |
36
|
|
|
* @return object|\Symfony\Component\Console\Output\OutputInterface |
37
|
|
|
*/ |
38
|
9 |
|
protected function execute(InputInterface $input, OutputInterface $output) |
39
|
|
|
{ |
40
|
9 |
|
list($filenames, $migrations) = $this->getMigrations(APPPATH . 'migrations'); |
41
|
|
|
|
42
|
9 |
|
$current = $this->getLatestVersion(true); |
43
|
6 |
|
$version = $input->getArgument('version'); |
44
|
|
|
|
45
|
6 |
|
$this->isValidVersion($migrations, $version); |
46
|
|
|
|
47
|
3 |
|
$migration = $version ?: $migrations[count($migrations) - 1]; |
48
|
3 |
|
$fileName = $filenames[count($migrations) - 1]; |
49
|
|
|
|
50
|
3 |
|
$this->migrate($current, $migration); |
51
|
|
|
|
52
|
3 |
|
$message = "Database is reverted back to version $migration ($fileName)"; |
53
|
|
|
|
54
|
3 |
|
return $output->writeln('<info>' . $message . '</info>'); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Checks if the version is valid to be rolled back. |
59
|
|
|
* |
60
|
|
|
* @param array $migrations |
61
|
|
|
* @param string $version |
62
|
|
|
* @return boolean |
63
|
|
|
*/ |
64
|
6 |
|
protected function isValidVersion(array $migrations, $version) |
65
|
|
|
{ |
66
|
6 |
|
foreach ($migrations as $migration) { |
67
|
6 |
|
if ($migration == $version || empty($version)) { |
68
|
3 |
|
return true; |
69
|
|
|
} |
70
|
3 |
|
} |
71
|
|
|
|
72
|
3 |
|
throw new \InvalidArgumentException('Cannot rollback to version ' . $version); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|