|
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
|
|
|
{ |
|
25
|
|
|
$this->eventDispatcher = $eventDispatcher; |
|
26
|
|
|
parent::__construct($promise); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
public function configure(): void |
|
30
|
|
|
{ |
|
31
|
|
|
$this |
|
32
|
|
|
->setDescription('Rollback last migration'); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
protected function execute(InputInterface $input, OutputInterface $output): int |
|
36
|
|
|
{ |
|
37
|
|
|
$migrations = $this->findMigrations($output); |
|
38
|
|
|
// check any executed migration |
|
39
|
|
|
$exist = false; |
|
40
|
|
|
foreach ($migrations as $migration) { |
|
41
|
|
|
if ($migration->getState()->getStatus() === State::STATUS_EXECUTED) { |
|
42
|
|
|
$exist = true; |
|
43
|
|
|
break; |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
if (!$exist) { |
|
47
|
|
|
$output->writeln('<fg=red>No migration found for rollback</>'); |
|
48
|
|
|
return ExitCode::OK; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
$this->eventDispatcher->dispatch(new BeforeMigrate()); |
|
52
|
|
|
try { |
|
53
|
|
|
$this->promise->getMigrator()->rollback(); |
|
54
|
|
|
if (!$migration instanceof MigrationInterface) { |
|
|
|
|
|
|
55
|
|
|
throw new \Exception('Migration not found'); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
$state = $migration->getState(); |
|
59
|
|
|
$status = $state->getStatus(); |
|
60
|
|
|
$output->writeln( |
|
61
|
|
|
sprintf('<fg=cyan>%s</>: %s', $state->getName(), static::MIGRATION_STATUS[$status] ?? $status) |
|
62
|
|
|
); |
|
63
|
|
|
} finally { |
|
64
|
|
|
$this->eventDispatcher->dispatch(new AfterMigrate()); |
|
65
|
|
|
} |
|
66
|
|
|
return ExitCode::OK; |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|