1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Mtolhuys\LaravelSchematics\Actions\Migration; |
4
|
|
|
|
5
|
|
|
use Illuminate\Support\Str; |
6
|
|
|
use Illuminate\Support\Facades\File; |
7
|
|
|
use Mtolhuys\LaravelSchematics\Http\Requests\DeleteRelationRequest; |
8
|
|
|
use Mtolhuys\LaravelSchematics\Models\Migration; |
9
|
|
|
use Mtolhuys\LaravelSchematics\Services\ClassReader; |
10
|
|
|
|
11
|
|
|
class DeleteMigrationAction |
12
|
|
|
{ |
13
|
|
|
public |
14
|
|
|
$autoMigrate, |
15
|
|
|
$path; |
16
|
|
|
|
17
|
|
|
public function __construct() |
18
|
|
|
{ |
19
|
|
|
$this->autoMigrate = config('schematics.auto-migrate'); |
20
|
|
|
$this->path = base_path('database/migrations'); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param $request |
25
|
|
|
* @return string |
26
|
|
|
*/ |
27
|
|
|
public function execute($request) |
28
|
|
|
{ |
29
|
|
|
$migrations = scandir($this->path); |
30
|
|
|
|
31
|
|
|
foreach ($migrations as $migration) { |
32
|
|
|
if ($this->isRelatedMigration($migration, $request)) { |
33
|
|
|
if ($this->autoMigrate) { |
34
|
|
|
$this->down($migration); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
File::delete("$this->path/$migration"); |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Running down in case auto-migrate is turned on |
44
|
|
|
* |
45
|
|
|
* @param $migration |
46
|
|
|
*/ |
47
|
|
|
public function down($migration): void |
48
|
|
|
{ |
49
|
|
|
$file = "$this->path/$migration"; |
50
|
|
|
|
51
|
|
|
require_once $file; |
52
|
|
|
|
53
|
|
|
Migration::where('migration', pathinfo($migration, PATHINFO_FILENAME))->delete(); |
54
|
|
|
|
55
|
|
|
$migration = ClassReader::getClassName($file); |
56
|
|
|
|
57
|
|
|
try { |
58
|
|
|
(new $migration)->down(); |
59
|
|
|
} catch (\Throwable $e) {} |
|
|
|
|
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param $migration |
64
|
|
|
* @param $request |
65
|
|
|
* @return bool |
66
|
|
|
*/ |
67
|
|
|
private function isRelatedMigration($migration, $request): bool |
68
|
|
|
{ |
69
|
|
|
$content = file_get_contents("$this->path/$migration"); |
70
|
|
|
|
71
|
|
|
if ($request instanceof DeleteRelationRequest) { |
72
|
|
|
return strpos($content, "laravel-schematics-{$request['table']}-relation") !== false; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
$table = Str::plural(Str::snake( |
76
|
|
|
substr($request['name'], strrpos($request['name'], '\\') + 1) |
77
|
|
|
)); |
78
|
|
|
|
79
|
|
|
return strpos($content, "laravel-schematics-$table-model") !== false |
80
|
|
|
|| strpos($content, "laravel-schematics-$table-relation") !== false; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|