1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Umbrellio\Deploy\Console; |
6
|
|
|
|
7
|
|
|
use Illuminate\Console\Command; |
8
|
|
|
use Illuminate\Support\Collection; |
9
|
|
|
use Illuminate\Support\Facades\App; |
10
|
|
|
use Illuminate\Support\Facades\DB; |
11
|
|
|
use Illuminate\Support\Facades\File; |
12
|
|
|
use Illuminate\Support\Str; |
13
|
|
|
use SplFileInfo; |
14
|
|
|
|
15
|
|
|
class RollbackNewMigrations extends Command |
16
|
|
|
{ |
17
|
|
|
private const COMMAND = 'git ls-tree --name-only origin/master database/migrations/'; |
18
|
|
|
|
19
|
|
|
protected $signature = 'rollback_new_migrations:rollback'; |
20
|
|
|
protected $description = 'Rollback new migrations (default way for k8s staging)'; |
21
|
|
|
|
22
|
|
|
public function handle(): void |
23
|
|
|
{ |
24
|
|
|
if (App::environment('production')) { |
25
|
|
|
$this->error('It`s restricted to rollback new migrations on production.'); |
26
|
|
|
return; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
$migrationsFromMaster = collect(explode(PHP_EOL, shell_exec(self::COMMAND))) |
30
|
|
|
->filter() |
31
|
|
|
->map(fn (string $path) => new SplFileInfo(base_path($path))); |
32
|
|
|
$migrationsFromCurrent = collect(File::files(base_path('database/migrations'))); |
33
|
|
|
|
34
|
|
|
/** @var Collection|SplFileInfo[] $migrationsToRollback */ |
35
|
|
|
$migrationsToRollback = $migrationsFromCurrent->keyBy->getFileName() |
36
|
|
|
->diffKeys($migrationsFromMaster->keyBy->getFileName()) |
37
|
|
|
->sort(fn (SplFileInfo $file1, SplFileInfo $file2) => strcmp($file1->getFilename(), $file2->getFilename())) |
38
|
|
|
->reverse(); |
39
|
|
|
|
40
|
|
|
if ($migrationsToRollback->isEmpty()) { |
41
|
|
|
$this->info('There are no migrations to rollback.'); |
42
|
|
|
return; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
DB::transaction(function () use ($migrationsToRollback) { |
46
|
|
|
foreach ($migrationsToRollback as $migration) { |
47
|
|
|
$this->info('Rolling back: ' . $migration->getFilename()); |
48
|
|
|
$this->downMigrationFile($migration); |
49
|
|
|
} |
50
|
|
|
}); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
private function downMigrationFile(SplFileInfo $f): void |
54
|
|
|
{ |
55
|
|
|
require_once $f->getPathname(); |
56
|
|
|
$filename = explode('.php', $f->getRelativePathname())[0]; |
|
|
|
|
57
|
|
|
$class = Str::studly(implode('_', array_slice(explode('_', $filename), 4))); |
58
|
|
|
$migration = new $class(); |
59
|
|
|
if (method_exists($migration, 'down')) { |
60
|
|
|
$migration->down(); |
61
|
|
|
DB::table(config('database.migrations', 'migrations'))->where('migration', $filename)->delete(); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|