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
5 changes: 5 additions & 0 deletions src/Generators/MigrationGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ protected function buildDefinition(Model $model)
$definition .= self::INDENT . '$table->' . $model->softDeletesDataType() . '();' . PHP_EOL;
}

if ($model->morphTo()) {
$definition .= self::INDENT . sprintf('$table->unsignedBigInteger(\'%s\');', Str::lower($model->morphTo() . "_id")) . PHP_EOL;
$definition .= self::INDENT . sprintf('$table->string(\'%s\');', Str::lower($model->morphTo() . "_type")) . PHP_EOL;
}

if ($model->usesTimestamps()) {
$definition .= self::INDENT . '$table->' . $model->timestampsDataType() . '();' . PHP_EOL;
}
Expand Down
16 changes: 14 additions & 2 deletions src/Generators/ModelGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,21 @@ private function buildRelationships(Model $model)

$name = Str::beforeLast($name, '_id');
$class = Str::studly($class ?? $name);
$relationship = sprintf("\$this->%s(%s::class)", $type, '\\' . $model->fullyQualifiedNamespace() . '\\' . $class);

$method_name = $type === 'hasMany' || $type === 'belongsToMany' ? Str::plural($name) : $name;
if ($type === 'morphTo') {
$relationship = sprintf('$this->%s()', $type);
} elseif ($type === 'morphMany' || $type === 'morphOne') {
$relation = Str::of($name)->lower()->singular() . 'able';
$relationship = sprintf('$this->%s(%s::class, \'%s\')', $type, '\\' . $model->fullyQualifiedNamespace() . '\\' . $class, $relation);
} else {
$relationship = sprintf('$this->%s(%s::class)', $type, '\\' . $model->fullyQualifiedNamespace() . '\\' . $class);
}

if ($type === 'morphTo') {
$method_name = Str::lower($class);
} else {
$method_name = in_array($type, ['hasMany', 'belongsToMany', 'morphMany']) ? Str::plural($name) : $name;
}
$method = str_replace('DummyName', Str::camel($method_name), $template);
$method = str_replace('null', $relationship, $method);

Expand Down
9 changes: 8 additions & 1 deletion src/Lexers/ModelLexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ class ModelLexer implements Lexer
'belongsto' => 'belongsTo',
'hasone' => 'hasOne',
'hasmany' => 'hasMany',
'belongstomany' => 'belongsToMany'
'belongstomany' => 'belongsToMany',
'morphone' => 'morphOne',
'morphmany' => 'morphMany',
'morphto' => 'morphTo',
];

private static $dataTypes = [
Expand Down Expand Up @@ -149,6 +152,10 @@ private function buildModel(string $name, array $columns)
foreach ($columns['relationships'] as $type => $relationships) {
foreach (explode(',', $relationships) as $reference) {
$model->addRelationship(self::$relationships[strtolower($type)], trim($reference));

if ($type === 'morphTo') {
$model->setMorphTo(trim($reference));
}
}
}
}
Expand Down
11 changes: 11 additions & 0 deletions src/Models/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ class Model
private $primaryKey = 'id';
private $timestamps = 'timestamps';
private $softDeletes = false;
private $morphTo;
private $columns = [];
private $relationships = [];
private $pivotTables = [];
Expand Down Expand Up @@ -162,4 +163,14 @@ public function pivotTables(): array
{
return $this->pivotTables;
}

public function setMorphTo(string $reference)
{
$this->morphTo = $reference;
}

public function morphTo(): ?string
{
return $this->morphTo;
}
}
72 changes: 68 additions & 4 deletions tests/Feature/Generator/MigrationGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -305,8 +305,8 @@ public function output_also_creates_constraints_for_pivot_table_migration_larave
}

/**
* @test
*/
* @test
*/
public function output_does_not_duplicate_pivot_table_migration()
{
$this->files->expects('stub')
Expand Down Expand Up @@ -334,8 +334,8 @@ public function output_does_not_duplicate_pivot_table_migration()
}

/**
* @test
*/
* @test
*/
public function output_does_not_duplicate_pivot_table_migration_laravel6()
{
$app = \Mockery::mock();
Expand Down Expand Up @@ -422,6 +422,70 @@ public function output_creates_foreign_keys_with_nullable_chained_correctly_lara
$this->assertEquals(['created' => [$model_migration]], $this->subject->output($tree));
}

/**
* @test
*/
public function output_works_with_polymorphic_relationships()
{
$this->files->expects('stub')
->with('migration.stub')
->andReturn(file_get_contents('stubs/migration.stub'));

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

$post_migration = str_replace('timestamp', $now->copy()->subSeconds(2)->format('Y_m_d_His'), 'database/migrations/timestamp_create_posts_table.php');
$user_migration = str_replace('timestamp', $now->copy()->subSecond()->format('Y_m_d_His'), 'database/migrations/timestamp_create_users_table.php');
$image_migration = str_replace('timestamp', $now->format('Y_m_d_His'), 'database/migrations/timestamp_create_images_table.php');

$this->files->expects('put')
->with($post_migration, $this->fixture('migrations/polymorphic_relationships_posts_table.php'));
$this->files->expects('put')
->with($user_migration, $this->fixture('migrations/polymorphic_relationships_users_table.php'));
$this->files->expects('put')
->with($image_migration, $this->fixture('migrations/polymorphic_relationships_images_table.php'));

$tokens = $this->blueprint->parse($this->fixture('definitions/polymorphic-relationships.bp'));
$tree = $this->blueprint->analyze($tokens);

$this->assertEquals(['created' => [$post_migration, $user_migration, $image_migration]], $this->subject->output($tree));
}

/**
* @test
*/
public function output_works_with_polymorphic_relationships_laravel6()
{
$app = \Mockery::mock();
$app->shouldReceive('version')
->withNoArgs()
->andReturn('6.0.0');
App::swap($app);

$this->files->expects('stub')
->with('migration.stub')
->andReturn(file_get_contents('stubs/migration.stub'));

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

$post_migration = str_replace('timestamp', $now->copy()->subSeconds(2)->format('Y_m_d_His'), 'database/migrations/timestamp_create_posts_table.php');
$user_migration = str_replace('timestamp', $now->copy()->subSecond()->format('Y_m_d_His'), 'database/migrations/timestamp_create_users_table.php');
$image_migration = str_replace('timestamp', $now->format('Y_m_d_His'), 'database/migrations/timestamp_create_images_table.php');

$this->files->expects('put')
->with($post_migration, $this->fixture('migrations/polymorphic_relationships_posts_table_laravel6.php'));
$this->files->expects('put')
->with($user_migration, $this->fixture('migrations/polymorphic_relationships_users_table_laravel6.php'));
$this->files->expects('put')
->with($image_migration, $this->fixture('migrations/polymorphic_relationships_images_table_laravel6.php'));

$tokens = $this->blueprint->parse($this->fixture('definitions/polymorphic-relationships.bp'));
$tree = $this->blueprint->analyze($tokens);

$this->assertEquals(['created' => [$post_migration, $user_migration, $image_migration]], $this->subject->output($tree));
}

public function modelTreeDataProvider()
{
return [
Expand Down
53 changes: 49 additions & 4 deletions tests/Feature/Generator/ModelGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ public function output_generates_models($definition, $path, $model)
}

/**
* @test
*/
* @test
*/
public function output_works_for_pascal_case_definition()
{
$this->files->expects('stub')
Expand Down Expand Up @@ -164,6 +164,51 @@ public function output_generates_relationships()
$this->assertEquals(['created' => ['app/Subscription.php']], $this->subject->output($tree));
}

/**
* @test
*/
public function output_generates_polymorphic_relationships()
{
$this->files->expects('stub')
->with('model/class.stub')
->andReturn(file_get_contents('stubs/model/class.stub'));
$this->files->expects('stub')
->times(3)
->with('model/fillable.stub')
->andReturn(file_get_contents('stubs/model/fillable.stub'));
$this->files->expects('stub')
->times(3)
->with('model/casts.stub')
->andReturn(file_get_contents('stubs/model/casts.stub'));
$this->files->expects('stub')
->times(3)
->with('model/method.stub')
->andReturn(file_get_contents('stubs/model/method.stub'));

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

$this->files->expects('exists')
->with('app')
->andReturnTrue();
$this->files->expects('put')
->with('app/User.php', $this->fixture('models/user-polymorphic-relationship.php'));

$this->files->expects('exists')
->with('app')
->andReturnTrue();
$this->files->expects('put')
->with('app/Image.php', $this->fixture('models/image-polymorphic-relationship.php'));

$tokens = $this->blueprint->parse($this->fixture('definitions/polymorphic-relationships.bp'));
$tree = $this->blueprint->analyze($tokens);

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

/**
* @test
*/
Expand Down Expand Up @@ -326,8 +371,8 @@ public function output_generates_models_with_guarded_property_when_config_option
}

/**
* @test
*/
* @test
*/
public function output_generates_models_with_custom_namespace_correctly()
{
$definition = 'definitions/custom-models-namespace.bp';
Expand Down
36 changes: 36 additions & 0 deletions tests/Feature/Lexers/ModelLexerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,42 @@ public function it_stores_relationships()
$this->assertEquals(['Duration', 'Transaction:tid'], $relationships['hasOne']);
}

/**
* @test
*/
public function it_enables_morphable_and_set_its_reference()
{
$tokens = [
'models' => [
'Model' => [
'relationships' => [
'morphTo' => 'Morphable',
]
],
],
];

$actual = $this->subject->analyze($tokens);

$this->assertIsArray($actual['models']);
$this->assertCount(1, $actual['models']);

$model = $actual['models']['Model'];
$this->assertEquals('Model', $model->name());
$this->assertEquals('Morphable', $model->morphTo());
$this->assertTrue($model->usesTimestamps());

$columns = $model->columns();
$this->assertCount(1, $columns);
$this->assertEquals('id', $columns['id']->name());
$this->assertEquals('id', $columns['id']->dataType());
$this->assertEquals([], $columns['id']->modifiers());

$relationships = $model->relationships();
$this->assertCount(1, $relationships);
$this->assertEquals(['Morphable'], $relationships['morphTo']);
}

public function dataTypeAttributesDataProvider()
{
return [
Expand Down
15 changes: 15 additions & 0 deletions tests/fixtures/definitions/polymorphic-relationships.bp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
models:
Post:
name: string:400
relationships:
morphMany: Image

User:
name: string:400
relationships:
morphMany: Image

Image:
url: string:400
relationships:
morphTo: Imageable
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

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

class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('url', 400);
$table->unsignedBigInteger('imageable_id');
$table->string('imageable_type');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

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

class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('url', 400);
$table->unsignedBigInteger('imageable_id');
$table->string('imageable_type');
$table->timestamps();
});
}

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