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

UpCommand::execute()   B

Complexity

Conditions 6
Paths 21

Size

Total Lines 35
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 25
nc 21
nop 2
dl 0
loc 35
ccs 0
cts 32
cp 0
crap 42
rs 8.8977
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 UpCommand extends BaseMigrationCommand
18
{
19
    protected static $defaultName = 'migrate/up';
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('Execute all new migrations');
32
    }
33
34
    protected function execute(InputInterface $input, OutputInterface $output): int
35
    {
36
        $migrations = $this->findMigrations($output);
37
        // check any not executed migration
38
        $exist = false;
39
        foreach ($migrations as $migration) {
40
            if ($migration->getState()->getStatus() === State::STATUS_PENDING) {
41
                $exist = true;
42
                break;
43
            }
44
        }
45
        if (!$exist) {
46
            $output->writeln('<fg=red>No migration found for execute</>');
47
            return ExitCode::OK;
48
        }
49
        $migrator = $this->promise->getMigrator();
50
51
        $limit = PHP_INT_MAX;
52
        $this->eventDispatcher->dispatch(new BeforeMigrate());
53
        try {
54
            do {
55
                $migration = $migrator->run();
56
                if (!$migration instanceof MigrationInterface) {
57
                    break;
58
                }
59
60
                $state = $migration->getState();
61
                $status = $state->getStatus();
62
                $output->writeln('<fg=cyan>' . $state->getName() . '</>: '
63
                    . (static::MIGRATION_STATUS[$status] ?? $status));
64
            } while (--$limit > 0);
65
        } finally {
66
            $this->eventDispatcher->dispatch(new AfterMigrate());
67
        }
68
        return ExitCode::OK;
69
    }
70
}
71