Skip to content

Commit

Permalink
Remove all duplicates when overwriting migrations (laravel-shift#375)
Browse files Browse the repository at this point in the history
  • Loading branch information
Nathan Esayeas authored Sep 17, 2020
1 parent de322c2 commit 71a4f57
Showing 1 changed file with 29 additions and 9 deletions.
38 changes: 29 additions & 9 deletions src/Generators/MigrationGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Carbon\Carbon;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Str;
use Symfony\Component\Finder\SplFileInfo;

class MigrationGenerator implements Generator
{
Expand Down Expand Up @@ -37,6 +38,8 @@ class MigrationGenerator implements Generator
/** @var \Illuminate\Contracts\Filesystem\Filesystem */
private $files;

private $output = [];

private $hasForeignKeyConstraints = false;

public function __construct($files)
Expand All @@ -46,8 +49,6 @@ public function __construct($files)

public function output(Tree $tree, $overwrite = false): array
{
$output = [];

$created_pivot_tables = [];

$stub = $this->files->stub('migration.stub');
Expand All @@ -60,7 +61,7 @@ public function output(Tree $tree, $overwrite = false): array
$action = $this->files->exists($path) ? 'updated' : 'created';
$this->files->put($path, $this->populateStub($stub, $model));

$output[$action][] = $path;
$this->output[$action][] = $path;

if (! empty($model->pivotTables())) {
foreach ($model->pivotTables() as $pivotSegments) {
Expand All @@ -75,10 +76,10 @@ public function output(Tree $tree, $overwrite = false): array
$action = $this->files->exists($path) ? 'updated' : 'created';
$this->files->put($path, $this->populatePivotStub($stub, $pivotSegments));
$created_pivot_tables[] = $pivotTable;
$output[$action][] = $path;
$this->output[$action][] = $path;
}

return $output;
return $this->output;
}

public function types(): array
Expand Down Expand Up @@ -324,11 +325,30 @@ protected function getTablePath($tableName, Carbon $timestamp, $overwrite = fals
$dir = 'database/migrations/';
$name = '_create_'.$tableName.'_table.php';

$file = $overwrite ? collect($this->files->files($dir))->first(function ($file) use ($tableName) {
return str_contains($file, $tableName);
}) : false;
if ($overwrite) {
$migrations = collect($this->files->files($dir))
->filter(function (SplFileInfo $file) use ($name) {
return str_contains($file->getFilename(), $name);
})
->sort();

if ($migrations->isNotEmpty()) {
$migration = $migrations->first()->getPathname();

$migrations->diff($migration)
->each(function (SplFileInfo $file) {
$path = $file->getPathname();

$this->files->delete($path);

$this->output['deleted'][] = $path;
});

return $migration;
}
}

return $file ? (string) $file : $dir.$timestamp->format('Y_m_d_His').$name;
return $dir.$timestamp->format('Y_m_d_His').$name;
}

protected function isLaravel7orNewer()
Expand Down

0 comments on commit 71a4f57

Please sign in to comment.