Passed
Push — master ( 227314...d8a269 )
by Alexander
14:02
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
    {
25
        $this->eventDispatcher = $eventDispatcher;
26
        parent::__construct($promise);
27
    }
28
29
    public function configure(): void
30
    {
31
        $this
32
            ->setDescription('Execute all new migrations');
33
    }
34
35
    protected function execute(InputInterface $input, OutputInterface $output): int
36
    {
37
        $migrations = $this->findMigrations($output);
38
        // check any not executed migration
39
        $exist = false;
40
        foreach ($migrations as $migration) {
41
            if ($migration->getState()->getStatus() === State::STATUS_PENDING) {
42
                $exist = true;
43
                break;
44
            }
45
        }
46
        if (!$exist) {
47
            $output->writeln('<fg=red>No migration found for execute</>');
48
            return ExitCode::OK;
49
        }
50
        $migrator = $this->promise->getMigrator();
51
52
        $limit = PHP_INT_MAX;
53
        $this->eventDispatcher->dispatch(new BeforeMigrate());
54
        try {
55
            do {
56
                $migration = $migrator->run();
57
                if (!$migration instanceof MigrationInterface) {
58
                    break;
59
                }
60
61
                $state = $migration->getState();
62
                $status = $state->getStatus();
63
                $output->writeln('<fg=cyan>' . $state->getName() . '</>: '
64
                    . (static::MIGRATION_STATUS[$status] ?? $status));
65
            } while (--$limit > 0);
66
        } finally {
67
            $this->eventDispatcher->dispatch(new AfterMigrate());
68
        }
69
        return ExitCode::OK;
70
    }
71
}
72