Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 65 additions & 3 deletions src/Generators/MigrationGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public function __construct(Filesystem $filesystem)

public function output(Tree $tree, $overwrite = false): array
{
$tables = ['tableNames' => [], 'pivotTableNames' => []];
$tables = ['tableNames' => [], 'pivotTableNames' => [], 'polymorphicManyToManyTables' => []];

$stub = $this->filesystem->stub('migration.stub');
/**
Expand All @@ -74,6 +74,12 @@ public function output(Tree $tree, $overwrite = false): array
$tables['pivotTableNames'][$pivotTableName] = $this->populatePivotStub($stub, $pivotSegments);
}
}

if (!empty($model->polymorphicManyToManyTables())) {
foreach ($model->polymorphicManyToManyTables() as $tableName) {
$tables['polymorphicManyToManyTables'][Str::lower(Str::plural(Str::singular($tableName).'able'))] = $this->populatePolyStub($stub, $tableName);
}
}
}

return $this->createMigrations($tables, $overwrite);
Expand All @@ -89,7 +95,7 @@ protected function createMigrations(array $tables, $overwrite = false): array
$output = [];

$sequential_timestamp = \Carbon\Carbon::now()->copy()->subSeconds(
collect($tables['tableNames'])->merge($tables['pivotTableNames'])->count()
collect($tables['tableNames'])->merge($tables['pivotTableNames'])->merge($tables['polymorphicManyToManyTables'])->count()
);

foreach ($tables['tableNames'] as $tableName => $data) {
Expand All @@ -106,6 +112,14 @@ protected function createMigrations(array $tables, $overwrite = false): array

$output[$action][] = $path;
}

foreach ($tables['polymorphicManyToManyTables'] as $tableName => $data) {
$path = $this->getTablePath($tableName, $sequential_timestamp->addSecond(), $overwrite);
$action = $this->filesystem->exists($path) ? 'updated' : 'created';
$this->filesystem->put($path, $data);
$output[$action][] = $path;
}

return $output;
}

Expand All @@ -116,7 +130,7 @@ protected function populateStub(string $stub, Model $model)
$stub = str_replace('{{ definition }}', $this->buildDefinition($model), $stub);

if (Blueprint::useReturnTypeHints()) {
$stub = str_replace(['up()','down()'], ['up(): void','down(): void'], $stub);
$stub = str_replace(['up()', 'down()'], ['up(): void', 'down(): void'], $stub);
}

if ($this->hasForeignKeyConstraints) {
Expand All @@ -139,6 +153,23 @@ protected function populatePivotStub(string $stub, array $segments)
return $stub;
}

protected function populatePolyStub(string $stub, string $parentTable)
{
$stub = str_replace('{{ class }}', $this->getPolyClassName($parentTable), $stub);
$stub = str_replace('{{ table }}', $this->getPolyTableName($parentTable), $stub);
$stub = str_replace('{{ definition }}', $this->buildPolyTableDefinition($parentTable), $stub);

if (Blueprint::useReturnTypeHints()) {
$stub = str_replace(['up()', 'down()'], ['up(): void', 'down(): void'], $stub);
}

if ($this->hasForeignKeyConstraints) {
$stub = $this->disableForeignKeyConstraints($stub);
}

return $stub;
}

protected function buildDefinition(Model $model)
{
$definition = '';
Expand Down Expand Up @@ -286,6 +317,27 @@ protected function buildPivotTableDefinition(array $segments)
return trim($definition);
}

protected function buildPolyTableDefinition(string $parentTable)
{
$definition = '';

$references = 'id';
$on = Str::lower(Str::plural($parentTable));
$foreign = Str::lower(Str::singular($parentTable)) . '_' . $references;

if (config('blueprint.use_constraints')) {
$this->hasForeignKeyConstraints = true;
$definition .= $this->buildForeignKey($foreign, $on, 'id') . ';' . PHP_EOL;
} else {
$definition .= self::INDENT . '$table->foreignId(\'' . $foreign . '\');' . PHP_EOL;
}

$definition .= self::INDENT . sprintf('$table->unsignedBigInteger(\'%s\');', Str::lower(Str::singular($parentTable).'able' . '_id')) . PHP_EOL;
$definition .= self::INDENT . sprintf('$table->string(\'%s\');', Str::lower(Str::singular($parentTable).'able' . '_type')) . PHP_EOL;

return trim($definition);
}

protected function buildForeignKey(string $column_name, ?string $on, string $type, array $attributes = [], array $modifiers = [])
{
if (is_null($on)) {
Expand Down Expand Up @@ -409,6 +461,11 @@ protected function getPivotClassName(array $segments)
return 'Create' . Str::studly($this->getPivotTableName($segments)) . 'Table';
}

protected function getPolyClassName(string $parentTable)
{
return 'Create' . Str::studly($this->getPolyTableName($parentTable)) . 'Table';
}

protected function getPivotTableName(array $segments)
{
$isCustom = collect($segments)
Expand All @@ -435,6 +492,11 @@ function ($name) {
return strtolower(implode('_', $segments));
}

protected function getPolyTableName(string $parentTable)
{
return Str::plural(Str::lower(Str::singular($parentTable) . 'able'));
}

private function shouldAddForeignKeyConstraint(\Blueprint\Models\Column $column)
{
if ($column->name() === 'id') {
Expand Down
6 changes: 4 additions & 2 deletions src/Generators/ModelGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,11 @@ protected function buildRelationships(Model $model)

if ($type === 'morphTo') {
$relationship = sprintf('$this->%s()', $type);
} elseif ($type === 'morphMany' || $type === 'morphOne') {
} elseif (in_array($type, ['morphMany', 'morphOne', 'morphToMany'])) {
$relation = Str::lower($is_model_fqn ? Str::singular(Str::afterLast($column_name, '\\')) : Str::singular($column_name)) . 'able';
$relationship = sprintf('$this->%s(%s::class, \'%s\')', $type, $fqcn, $relation);
} elseif ($type === 'morphedByMany') {
$relationship = sprintf('$this->%s(%s::class, \'%sable\')', $type, $fqcn, strtolower($model->name()));
} elseif (!is_null($key)) {
$relationship = sprintf('$this->%s(%s::class, \'%s\', \'%s\')', $type, $fqcn, $column_name, $key);
} elseif (!is_null($class) && $type === 'belongsToMany') {
Expand All @@ -226,7 +228,7 @@ protected function buildRelationships(Model $model)

if ($type === 'morphTo') {
$method_name = Str::lower($class_name);
} elseif (in_array($type, ['hasMany', 'belongsToMany', 'morphMany'])) {
} elseif (in_array($type, ['hasMany', 'belongsToMany', 'morphMany', 'morphToMany', 'morphedByMany'])) {
$method_name = Str::plural($is_model_fqn ? Str::afterLast($column_name, '\\') : $column_name);
}

Expand Down
2 changes: 2 additions & 0 deletions src/Lexers/ModelLexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ class ModelLexer implements Lexer
'morphone' => 'morphOne',
'morphmany' => 'morphMany',
'morphto' => 'morphTo',
'morphtomany' => 'morphToMany',
'morphedbymany' => 'morphedByMany',
];

private static $dataTypes = [
Expand Down
14 changes: 14 additions & 0 deletions src/Models/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class Model
private $columns = [];
private $relationships = [];
private $pivotTables = [];
private $polymorphicManyToManyTables = [];
private $indexes = [];

/**
Expand Down Expand Up @@ -149,10 +150,18 @@ public function addRelationship(string $type, string $reference)
if ($type === 'belongsToMany') {
$this->addPivotTable($reference);
}
if ($type === 'morphedByMany') {
$this->addPolymorphicManyToManyTable(Str::studly($this->tableName()));
}

$this->relationships[$type][] = $reference;
}

public function addPolymorphicManyToManyTable(string $reference)
{
$this->polymorphicManyToManyTables[] = class_basename($reference);
}

public function addPivotTable(string $reference)
{
$segments = [$this->name(), class_basename($reference)];
Expand All @@ -175,6 +184,11 @@ public function pivotTables(): array
return $this->pivotTables;
}

public function polymorphicManyToManyTables()
{
return $this->polymorphicManyToManyTables;
}

public function setMorphTo(string $reference)
{
$this->morphTo = $reference;
Expand Down
28 changes: 28 additions & 0 deletions tests/Feature/Generators/MigrationGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,34 @@ public function output_creates_pivot_table_migration_correctly_when_model_name_c
$this->assertEquals(['created' => [$model_migration, $pivot_migration]], $this->subject->output($tree));
}

/**
* @test
*/
public function output_also_creates_many_to_many_polymorphic_intermediate_table_migration()
{
$this->filesystem->expects('stub')
->with('migration.stub')
->andReturn($this->stub('migration.stub'));

$now = Carbon::now();
Carbon::setTestNow($now);

$model_migration = str_replace('timestamp', $now->copy()->subSecond()->format('Y_m_d_His'), 'database/migrations/timestamp_create_tags_table.php');
$poly_migration = str_replace('timestamp', $now->format('Y_m_d_His'), 'database/migrations/timestamp_create_tagables_table.php');

$this->filesystem->expects('exists')->twice()->andReturn(false);

$this->filesystem->expects('put')
->with($model_migration, $this->fixture('migrations/morphed-by-many.php'));
$this->filesystem->expects('put')
->with($poly_migration, $this->fixture('migrations/morphed-by-many-intermediate.php'));

$tokens = $this->blueprint->parse($this->fixture('drafts/morphed-by-many.yaml'));
$tree = $this->blueprint->analyze($tokens);

$this->assertEquals(['created' => [$model_migration, $poly_migration]], $this->subject->output($tree));
}

/**
* @test
*/
Expand Down
46 changes: 46 additions & 0 deletions tests/Feature/Generators/ModelGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,52 @@ public function output_generates_polymorphic_relationships()
$this->assertEquals(['created' => ['app/Post.php', 'app/User.php', 'app/Image.php']], $this->subject->output($tree));
}

/**
* @test
*/
public function output_generates_morphtomany_relationship_with_intermediate_models()
{
$this->filesystem->expects('stub')
->with($this->modelStub)
->andReturn($this->stub($this->modelStub));
$this->filesystem->expects('stub')
->times(3)
->with('model.fillable.stub')
->andReturn($this->stub('model.fillable.stub'));

$this->filesystem->expects('stub')
->times(3)
->with('model.casts.stub')
->andReturn($this->stub('model.casts.stub'));
$this->filesystem->expects('stub')
->times(3)
->with('model.method.stub')
->andReturn($this->stub('model.method.stub'));

$this->filesystem->expects('exists')
->with('app')
->andReturnTrue();
$this->filesystem->expects('put')
->with('app/Post.php', $this->fixture('models/post-many-to-many-polymorphic-relationship.php'));

$this->filesystem->expects('exists')
->with('app')
->andReturnTrue();
$this->filesystem->expects('put')
->with('app/Video.php', $this->fixture('models/video-many-to-many-polymorphic-relationship.php'));

$this->filesystem->expects('exists')
->with('app')
->andReturnTrue();
$this->filesystem->expects('put')
->with('app/Tag.php', $this->fixture('models/tag-many-to-many-polymorphic-relationship.php'));

$tokens = $this->blueprint->parse($this->fixture('drafts/many-to-many-polymorphic-relationships.yaml'));
$tree = $this->blueprint->analyze($tokens);

$this->assertEquals(['created' => ['app/Post.php', 'app/Video.php', 'app/Tag.php']], $this->subject->output($tree));
}

/**
* @test
*/
Expand Down
15 changes: 15 additions & 0 deletions tests/fixtures/drafts/many-to-many-polymorphic-relationships.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
models:
Post:
name: string
relationships:
morphToMany: Tag

Video:
name: string
relationships:
morphToMany: Tag

Tag:
name: string
relationships:
morphedByMany: Post, Video
5 changes: 5 additions & 0 deletions tests/fixtures/drafts/morphed-by-many.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
models:
Tag:
name: string
relationships:
morphedByMany: Video
32 changes: 32 additions & 0 deletions tests/fixtures/migrations/morphed-by-many-intermediate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTagablesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tagables', function (Blueprint $table) {
$table->foreignId('tag_id');
$table->unsignedBigInteger('tagable_id');
$table->string('tagable_type');
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tagables');
}
}
32 changes: 32 additions & 0 deletions tests/fixtures/migrations/morphed-by-many.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTagsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tags');
}
}
Loading