Passed
Pull Request — master (#23)
by
unknown
03:34
created

DownCommand::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 4
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Cycle\Command\Migration;
6
7
use Psr\EventDispatcher\EventDispatcherInterface;
8
use Spiral\Migrations\MigrationInterface;
9
use Spiral\Migrations\State;
10
use Symfony\Component\Console\Input\InputInterface;
11
use Symfony\Component\Console\Output\OutputInterface;
12
use Yiisoft\Yii\Console\ExitCode;
13
use Yiisoft\Yii\Cycle\Command\CycleDependencyPromise;
14
use Yiisoft\Yii\Cycle\Event\AfterMigrate;
15
use Yiisoft\Yii\Cycle\Event\BeforeMigrate;
16
17
final class DownCommand extends BaseMigrationCommand
18
{
19
    protected static $defaultName = 'migrate/down';
20
21
    private EventDispatcherInterface $eventDispatcher;
22
23
    public function __construct(CycleDependencyPromise $promise, EventDispatcherInterface $eventDispatcher) {
24
        $this->eventDispatcher = $eventDispatcher;
25
        parent::__construct($promise);
26
    }
27
28
    public function configure(): void
29
    {
30
        $this
31
            ->setDescription('Rollback last migration');
32
    }
33
34
    protected function execute(InputInterface $input, OutputInterface $output): int
35
    {
36
        $migrations = $this->findMigrations($output);
37
        // check any executed migration
38
        $exist = false;
39
        foreach ($migrations as $migration) {
40
            if ($migration->getState()->getStatus() === State::STATUS_EXECUTED) {
41
                $exist = true;
42
                break;
43
            }
44
        }
45
        if (!$exist) {
46
            $output->writeln('<fg=red>No migration found for rollback</>');
47
            return ExitCode::OK;
48
        }
49
50
        $this->eventDispatcher->dispatch(new BeforeMigrate());
51
        try {
52
            $this->promise->getMigrator()->rollback();
53
            if (!$migration instanceof MigrationInterface) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $migration seems to be defined by a foreach iteration on line 39. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
54
                throw new \Exception('Migration not found');
55
            }
56
57
            $state = $migration->getState();
58
            $status = $state->getStatus();
59
            $output->writeln(
60
                sprintf('<fg=cyan>%s</>: %s', $state->getName(), static::MIGRATION_STATUS[$status] ?? $status)
61
            );
62
        } finally {
63
            $this->eventDispatcher->dispatch(new AfterMigrate());
64
        }
65
        return ExitCode::OK;
66
    }
67
}
68