Completed
Push — master ( dc7866...8155ff )
by Changwan
06:46
created

MigrateRollbackCommand::execute()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 13
nc 5
nop 0
dl 0
loc 22
rs 8.6737
c 0
b 0
f 0
1
<?php
2
namespace Wandu\Database\Commands;
3
4
use Wandu\Console\Command;
5
use Wandu\Database\Migrator\Migrator;
6
7
class MigrateRollbackCommand extends Command
8
{
9
    /** @var string */
10
    protected $description = 'Run rollback.';
11
12
    /** @var array */
13
    protected $arguments = [
14
        'until?' => 'the migrate id for the rollback',
15
    ];
16
17
    /** @var \Wandu\Database\Migrator\Migrator */
18
    protected $manager;
19
20
    /**
21
     * @param \Wandu\Database\Migrator\Migrator $manager
22
     */
23
    public function __construct(Migrator $manager)
24
    {
25
        $this->manager = $manager;
26
    }
27
    
28
    public function execute()
29
    {
30
        $untilMigrationId = $this->input->getArgument('until');
31
        
32
        /** @var \Wandu\Database\Migrator\MigrationContainer[] $migrations */
33
        $migrations = array_reverse($this->manager->migrations());
34
35
        if (!count($migrations)) {
36
            $this->output->writeln("<comment>there is no migration to rollback.</comment>");
37
            return 2;
38
        }
39
        foreach ($migrations as $migration) {
40
            if (!$migration->isApplied()) {
41
                continue;
42
            }
43
            $this->manager->down($migration->getId());
44
            $this->output->writeln(sprintf("<info>down</info> %s", $migration->getId()));
45
            if ($migration->getId() === $untilMigrationId || !$untilMigrationId) {
46
                break;
47
            }
48
        }
49
    }
50
}
51