Passed
Push — master ( 9c8ace...d62147 )
by Alexander
13:22
created

UpCommand::execute()   B

Complexity

Conditions 6
Paths 21

Size

Total Lines 34
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 6
eloc 24
c 2
b 0
f 1
nc 21
nop 2
dl 0
loc 34
ccs 0
cts 10
cp 0
crap 42
rs 8.9137
1
<?php
2
3
namespace Yiisoft\Yii\Cycle\Command;
4
5
use Psr\EventDispatcher\EventDispatcherInterface;
6
use Spiral\Database\DatabaseManager;
7
use Spiral\Migrations\Config\MigrationConfig;
8
use Spiral\Migrations\MigrationInterface;
9
use Spiral\Migrations\Migrator;
10
use Spiral\Migrations\State;
11
use Symfony\Component\Console\Input\InputInterface;
12
use Symfony\Component\Console\Output\OutputInterface;
13
use Yiisoft\Yii\Console\ExitCode;
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(
24
        DatabaseManager $dbal,
25
        MigrationConfig $conf,
26
        Migrator $migrator,
27
        EventDispatcherInterface $eventDispatcher
28
    ) {
29
        parent::__construct($dbal, $conf, $migrator);
30
        $this->eventDispatcher = $eventDispatcher;
31
    }
32
33
    public function configure(): void
34
    {
35
        $this
36
            ->setDescription('Execute all new migrations');
37
    }
38
39
    protected function execute(InputInterface $input, OutputInterface $output): int
40
    {
41
        $migrations = $this->findMigrations($output);
42
        // check any not executed migration
43
        $exist = false;
44
        foreach ($migrations as $migration) {
45
            if ($migration->getState()->getStatus() === State::STATUS_PENDING) {
46
                $exist = true;
47
                break;
48
            }
49
        }
50
        if (!$exist) {
51
            $output->writeln('<fg=red>No migration found for execute</>');
52
            return ExitCode::OK;
53
        }
54
55
        $limit = PHP_INT_MAX;
56
        $this->eventDispatcher->dispatch(new BeforeMigrate());
57
        try {
58
            do {
59
                $migration = $this->migrator->run();
60
                if (!$migration instanceof MigrationInterface) {
61
                    break;
62
                }
63
64
                $state = $migration->getState();
65
                $status = $state->getStatus();
66
                $output->writeln('<fg=cyan>' . $state->getName() . '</>: '
67
                    . (static::MIGRATION_STATUS[$status] ?? $status));
68
            } while (--$limit > 0);
69
        } finally {
70
            $this->eventDispatcher->dispatch(new AfterMigrate());
71
        }
72
        return ExitCode::OK;
73
    }
74
}
75