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
20 changes: 16 additions & 4 deletions src/Generators/FactoryGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ class FactoryGenerator implements Generator
/** @var \Illuminate\Contracts\Filesystem\Filesystem */
private $files;

/** @var Tree */
private $tree;

private $imports = [];

public function __construct($files)
Expand All @@ -26,6 +29,8 @@ public function __construct($files)

public function output(Tree $tree): array
{
$this->tree = $tree;

$output = [];

if (Blueprint::isLaravel8OrHigher()) {
Expand Down Expand Up @@ -127,9 +132,10 @@ protected function buildDefinition(Model $model)
}

$class = Str::studly(Str::singular($table));
$reference = $this->fullyQualifyModelReference($class) ?? $model;

if (Blueprint::isLaravel8OrHigher()) {
$this->addImport($model, $model->fullyQualifiedNamespace() . '\\' . $class);
$this->addImport($model, $reference->fullyQualifiedNamespace() . '\\' . $class);
}
if ($key === 'id') {
if (Blueprint::isLaravel8OrHigher()) {
Expand All @@ -138,7 +144,7 @@ protected function buildDefinition(Model $model)
$definition .= ',' . PHP_EOL;
} else {
$definition .= str_repeat(self::INDENT, 2) . "'{$column->name()}' => ";
$definition .= sprintf('factory(%s::class)', '\\' . $model->fullyQualifiedNamespace() . '\\' . $class);
$definition .= sprintf('factory(%s::class)', '\\' . $reference->fullyQualifiedNamespace() . '\\' . $class);
$definition .= ',' . PHP_EOL;
}
} else {
Expand All @@ -157,14 +163,15 @@ protected function buildDefinition(Model $model)
} elseif ($column->dataType() === 'id' || ($column->dataType() === 'uuid' && Str::endsWith($column->name(), '_id'))) {
$name = Str::beforeLast($column->name(), '_id');
$class = Str::studly($column->attributes()[0] ?? $name);
$reference = $this->fullyQualifyModelReference($class) ?? $model;

if (Blueprint::isLaravel8OrHigher()) {
$this->addImport($model, $model->fullyQualifiedNamespace() . '\\' . $class);
$this->addImport($model, $reference->fullyQualifiedNamespace() . '\\' . $class);
$definition .= str_repeat(self::INDENT, 3) . "'{$column->name()}' => ";
$definition .= sprintf('%s::factory()', $class);
} else {
$definition .= str_repeat(self::INDENT, 2) . "'{$column->name()}' => ";
$definition .= sprintf('factory(%s::class)', '\\' . $model->fullyQualifiedNamespace() . '\\' . $class);
$definition .= sprintf('factory(%s::class)', '\\' . $reference->fullyQualifiedNamespace() . '\\' . $class);
}
$definition .= ',' . PHP_EOL;
} elseif (in_array($column->dataType(), ['enum', 'set']) && !empty($column->attributes())) {
Expand Down Expand Up @@ -286,4 +293,9 @@ private function fillableColumns(array $columns): array
return !in_array('nullable', $column->modifiers());
});
}

private function fullyQualifyModelReference(string $model_name)
{
return $this->tree->modelForContext($model_name);
}
}
34 changes: 28 additions & 6 deletions src/Generators/ModelGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,18 @@ class ModelGenerator implements Generator
/** @var \Illuminate\Contracts\Filesystem\Filesystem */
private $files;

/** @var Tree */
private $tree;

public function __construct($files)
{
$this->files = $files;
}

public function output(Tree $tree): array
{
$this->tree = $tree;

$output = [];

if (Blueprint::isLaravel8OrHigher()) {
Expand Down Expand Up @@ -210,19 +215,20 @@ protected function buildRelationships(Model $model)
}

$class_name = Str::studly($class ?? $method_name);
$fqcn = $this->fullyQualifyModelReference($class_name) ?? $model->fullyQualifiedNamespace() . '\\' . $class_name;

if ($type === 'morphTo') {
$relationship = sprintf('$this->%s()', $type);
} elseif ($type === 'morphMany' || $type === 'morphOne') {
$relation = Str::lower(Str::singular($column_name)) . 'able';
$relationship = sprintf('$this->%s(%s::class, \'%s\')', $type, '\\' . $model->fullyQualifiedNamespace() . '\\' . $class_name, $relation);
} elseif (! is_null($key)) {
$relationship = sprintf('$this->%s(%s::class, \'%s\', \'%s\')', $type, '\\' . $model->fullyQualifiedNamespace() . '\\' . $class_name, $column_name, $key);
} elseif (! is_null($class) && $type === 'belongsToMany') {
$relationship = sprintf('$this->%s(%s::class, \'%s\')', $type, '\\' . $model->fullyQualifiedNamespace() . '\\' . $class_name, $column_name);
$relationship = sprintf('$this->%s(%s::class, \'%s\')', $type, '\\' . $fqcn, $relation);
} elseif (!is_null($key)) {
$relationship = sprintf('$this->%s(%s::class, \'%s\', \'%s\')', $type, '\\' . $fqcn, $column_name, $key);
} elseif (!is_null($class) && $type === 'belongsToMany') {
$relationship = sprintf('$this->%s(%s::class, \'%s\')', $type, '\\' . $fqcn, $column_name);
$column_name = $class;
} else {
$relationship = sprintf('$this->%s(%s::class)', $type, '\\' . $model->fullyQualifiedNamespace() . '\\' . $class_name);
$relationship = sprintf('$this->%s(%s::class)', $type, '\\' . $fqcn);
}

if ($type === 'morphTo') {
Expand Down Expand Up @@ -408,4 +414,20 @@ private function phpDataType(string $dataType)

return $php_data_types[strtolower($dataType)] ?? 'string';
}

private function fullyQualifyModelReference(string $model_name)
{
// TODO: get model_name from tree.
// If not found, assume parallel namespace as controller.
// Use respond-statement.php as test case.

/** @var \Blueprint\Models\Model $model */
$model = $this->tree->modelForContext($model_name);

if (isset($model)) {
return $model->fullyQualifiedClassName();
}

return null;
}
}
2 changes: 1 addition & 1 deletion src/Tree.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public function modelForContext(string $context)
});

if (count($matches) === 1) {
return $this->models[$matches[0]];
return $this->models[current($matches)];
}
}

Expand Down
36 changes: 36 additions & 0 deletions tests/Feature/Generators/FactoryGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,42 @@ public function output_using_return_types()
$this->assertEquals(['created' => ['database/factories/PostFactory.php']], $this->subject->output($tree));
}

/**
* @test
* @environment-setup useLaravel8
*/
public function output_generates_references_for_nested_models()
{
$this->files->expects('stub')
->with($this->factoryStub)
->andReturn($this->stub($this->factoryStub));

$this->files->expects('exists')
->times(4)
->andReturnTrue();

$this->files->expects('put')
->with('database/factories/QuestionTypeFactory.php', \Mockery::type('string'));
$this->files->expects('put')
->with('database/factories/Appointment/AppointmentTypeFactory.php', \Mockery::type('string'));
$this->files->expects('put')
->with('database/factories/Screening/ReportFactory.php', \Mockery::type('string'));
$this->files->expects('put')
->with('database/factories/Screening/ScreeningQuestionFactory.php', $this->fixture('factories/nested-models-laravel8.php'));

$tokens = $this->blueprint->parse($this->fixture('drafts/nested-models.yaml'));
$tree = $this->blueprint->analyze($tokens);

$this->assertEquals([
'created' => [
'database/factories/QuestionTypeFactory.php',
'database/factories/Appointment/AppointmentTypeFactory.php',
'database/factories/Screening/ReportFactory.php',
'database/factories/Screening/ScreeningQuestionFactory.php',
],
], $this->subject->output($tree));
}

/**
* @test
* @environment-setup useLaravel8
Expand Down
49 changes: 49 additions & 0 deletions tests/Feature/Generators/ModelGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,55 @@ public function output_generates_models_with_guarded_property_when_config_option
$this->assertEquals(['created' => ['app/Comment.php']], $this->subject->output($tree));
}

/**
* @test
* @environment-setup useLaravel8
*/
public function output_generates_models_with_namespaces_correctly()
{
$this->app['config']->set('blueprint.models_namespace', 'Models');

$this->files->expects('stub')
->with($this->modelStub)
->andReturn($this->stub($this->modelStub));
$this->files->expects('stub')
->times(4)
->with('model.fillable.stub')
->andReturn($this->stub('model.fillable.stub'));
$this->files->expects('stub')
->times(4)
->with('model.casts.stub')
->andReturn($this->stub('model.casts.stub'));
$this->files->expects('stub')
->times(4)
->with('model.method.stub')
->andReturn($this->stub('model.method.stub'));

$this->files->expects('exists')
->times(4)
->andReturnTrue();
$this->files->expects('put')
->with('app/Models/QuestionType.php', \Mockery::type('string'));
$this->files->expects('put')
->with('app/Models/Appointment/AppointmentType.php', \Mockery::type('string'));
$this->files->expects('put')
->with('app/Models/Screening/Report.php', \Mockery::type('string'));
$this->files->expects('put')
->with('app/Models/Screening/ScreeningQuestion.php', $this->fixture('models/nested-models-laravel8.php'));

$tokens = $this->blueprint->parse($this->fixture('drafts/nested-models.yaml'));
$tree = $this->blueprint->analyze($tokens);

$this->assertEquals([
'created' => [
'app/Models/QuestionType.php',
'app/Models/Appointment/AppointmentType.php',
'app/Models/Screening/Report.php',
'app/Models/Screening/ScreeningQuestion.php',
],
], $this->subject->output($tree));
}

/**
* @test
* @environment-setup useLaravel8
Expand Down
14 changes: 14 additions & 0 deletions tests/fixtures/drafts/nested-models.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
models:
QuestionType:
description: string

Appointment/AppointmentType:
name: string

Screening/Report:
name: string

Screening/ScreeningQuestion:
report_id: id
appointment_type_id: id
question_type_id: id
34 changes: 34 additions & 0 deletions tests/fixtures/factories/nested-models-laravel8.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
use App\Appointment\AppointmentType;
use App\QuestionType;
use App\Screening\Report;
use App\Screening\ScreeningQuestion;

class ScreeningQuestionFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = ScreeningQuestion::class;

/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'report_id' => Report::factory(),
'appointment_type_id' => AppointmentType::factory(),
'question_type_id' => QuestionType::factory(),
];
}
}
50 changes: 50 additions & 0 deletions tests/fixtures/models/nested-models-laravel8.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace App\Models\Screening;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ScreeningQuestion extends Model
{
use HasFactory;

/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'report_id',
'appointment_type_id',
'question_type_id',
];

/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'id' => 'integer',
'report_id' => 'integer',
'appointment_type_id' => 'integer',
'question_type_id' => 'integer',
];


public function report()
{
return $this->belongsTo(\App\Models\Screening\Report::class);
}

public function appointmentType()
{
return $this->belongsTo(\App\Models\Appointment\AppointmentType::class);
}

public function questionType()
{
return $this->belongsTo(\App\Models\QuestionType::class);
}
}