Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add model generator tests #70

Open
wants to merge 22 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
6 changes: 3 additions & 3 deletions src/Generators/EntityGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ abstract class EntityGenerator
protected $paths = [];
protected $model;
protected $fields;
protected $relations;
protected $relations = [];
protected $crudOptions;

/**
Expand Down Expand Up @@ -213,14 +213,14 @@ protected function getModelClass(string $model): string
return "{$modelNamespace}\\{$model}";
}

protected function isStubExists(string $stubName): bool
protected function isStubExists(string $stubName, ?string $generationType = null): bool
{
$config = "entity-generator.stubs.{$stubName}";

$stubPath = config($config);

if (!view()->exists($stubPath)) {
$generationType = Str::replace('_', ' ', $stubName);
$generationType ??= Str::replace('_', ' ', $stubName);

$message = "Generation of {$generationType} has been skipped cause the view {$stubPath} from the config {$config} is not exists. Please check that config has the correct view name value.";

Expand Down
34 changes: 17 additions & 17 deletions src/Generators/ModelGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,22 @@

class ModelGenerator extends EntityGenerator
{
CONST PLURAL_NUMBER_REQUIRED = [
protected const array PLURAL_NUMBER_REQUIRED = [
'belongsToMany',
'hasMany'
'hasMany',
];

public function generate(): void
{
if ($this->classExists('models', $this->model)) {
$this->throwFailureException(
ClassAlreadyExistsException::class,
"Cannot create {$this->model} Model cause {$this->model} Model already exists.",
"Remove {$this->model} Model."
exceptionClass: ClassAlreadyExistsException::class,
failureMessage: "Cannot create {$this->model} Model cause {$this->model} Model already exists.",
recommendedMessage: "Remove {$this->model} Model.",
);
}

if ($this->isStubExists('model') && ($this->isStubExists('relation') || empty($this->relations))) {
if ($this->isStubExists('model') && (collect($this->relations)->every(fn ($relation) => empty($relation)) || $this->isStubExists('relation', 'model'))) {
DenTray marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if ($this->isStubExists('model') && (collect($this->relations)->every(fn ($relation) => empty($relation)) || $this->isStubExists('relation', 'model'))) {
if ($this->isStubExists('model') && (!$this->hasRelations() || $this->isStubExists('relation', 'model'))) {

$this->prepareRelatedModels();
$modelContent = $this->getNewModelContent();

Expand All @@ -42,7 +42,7 @@ protected function getNewModelContent(): string
'fields' => Arr::collapse($this->fields),
'relations' => $this->prepareRelations(),
'casts' => $this->getCasts($this->fields),
'namespace' => $this->getOrCreateNamespace('models')
'namespace' => $this->getOrCreateNamespace('models'),
]);
}

Expand All @@ -59,9 +59,9 @@ public function prepareRelatedModels(): void
foreach ($relationsByType as $relation) {
if (!$this->classExists('models', $relation)) {
$this->throwFailureException(
ClassNotExistsException::class,
"Cannot create {$relation} Model cause {$relation} Model does not exists.",
"Create a {$relation} Model by himself or run command 'php artisan make:entity {$relation} --only-model'."
exceptionClass: ClassNotExistsException::class,
failureMessage: "Cannot create {$this->model} Model cause relation model {$relation} does not exist.",
recommendedMessage: "Create the {$relation} Model by himself or run command 'php artisan make:entity {$relation} --only-model'.",
);
}

Expand All @@ -70,7 +70,7 @@ public function prepareRelatedModels(): void
$newRelation = $this->getStub('relation', [
'name' => $this->getRelationName($this->model, $types[$type]),
'type' => $types[$type],
'entity' => $this->model
'entity' => $this->model,
]);

$fixedContent = preg_replace('/\}$/', "\n {$newRelation}\n}", $content);
Expand All @@ -80,9 +80,9 @@ public function prepareRelatedModels(): void
}
}

public function getModelContent($model): string
public function getModelContent(string $model): string
{
$modelPath = base_path($this->paths['models'] . "/{$model}.php");
$modelPath = base_path("{$this->paths['models']}/{$model}.php");

return file_get_contents($modelPath);
}
Expand All @@ -97,7 +97,7 @@ public function prepareRelations(): array
$result[] = [
'name' => $this->getRelationName($relation, $type),
'type' => $type,
'entity' => $relation
'entity' => $relation,
];
}
}
Expand All @@ -106,7 +106,7 @@ public function prepareRelations(): array
return $result;
}

protected function getCasts($fields): array
protected function getCasts(array $fields): array
{
$casts = [
'boolean-required' => 'boolean',
Expand All @@ -117,7 +117,7 @@ protected function getCasts($fields): array
$result = [];

foreach ($fields as $fieldType => $names) {
if (empty($casts[$fieldType])) {
if (!array_key_exists($fieldType, $casts)) {
continue;
}

Expand All @@ -129,7 +129,7 @@ protected function getCasts($fields): array
return $result;
}

private function getRelationName($relation, $type): string
private function getRelationName(string $relation, string $type): string
{
$relationName = Str::snake($relation);

Expand Down
9 changes: 5 additions & 4 deletions stubs/model.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,6 @@ class {{$entity}} extends Model
];

protected $hidden = ['pivot'];
@foreach($relations as $relation)

@include(config('entity-generator.stubs.relation'), $relation)
@endforeach
@if(!empty($casts))

protected $casts = [
Expand All @@ -26,4 +22,9 @@ class {{$entity}} extends Model
@endforeach
];
@endif
@foreach($relations as $relation)

@include(config('entity-generator.stubs.relation'), $relation)

@endforeach
}
2 changes: 1 addition & 1 deletion stubs/relation.blade.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
public function {{$name}}()
{
return $this->{{$type}}({{$entity}}::class);
}
}
8 changes: 0 additions & 8 deletions tests/ControllerGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace RonasIT\Support\Tests;

use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\View;
use RonasIT\Support\Events\SuccessCreateMessage;
use RonasIT\Support\Events\WarningEvent;
Expand All @@ -16,13 +15,6 @@ class ControllerGeneratorTest extends TestCase
{
use ControllerGeneratorMockTrait;

public function setUp(): void
{
parent::setUp();

Event::fake();
}

public function testControllerAlreadyExists()
{
$this->mockClass(ControllerGenerator::class, [
Expand Down
7 changes: 0 additions & 7 deletions tests/FactoryGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,6 @@ class FactoryGeneratorTest extends TestCase
{
use FactoryMockTrait;

public function setUp(): void
{
parent::setUp();

Event::fake();
}

public function testModelNotExists()
{
$this->assertExceptionThrew(
Expand Down
143 changes: 143 additions & 0 deletions tests/ModelGeneratorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
<?php

namespace RonasIT\Support\Tests;

use RonasIT\Support\Events\SuccessCreateMessage;
use RonasIT\Support\Events\WarningEvent;
use RonasIT\Support\Exceptions\ClassAlreadyExistsException;
use RonasIT\Support\Exceptions\ClassNotExistsException;
use RonasIT\Support\Generators\ModelGenerator;
use RonasIT\Support\Tests\Support\Model\ModelMockTrait;

class ModelGeneratorTest extends TestCase
{
use ModelMockTrait;

public function testModelAlreadyExists()
{
$this->mockClass(ModelGenerator::class, [
$this->classExistsMethodCall(['models', 'Post']),
]);

$this->assertExceptionThrew(
className: ClassAlreadyExistsException::class,
message: 'Cannot create Post Model cause Post Model already exists. Remove Post Model.',
);

app(ModelGenerator::class)
->setModel('Post')
->generate();
}

public function testRelationModelMissing()
{
$this->assertExceptionThrew(
className: ClassNotExistsException::class,
message: "Cannot create Post Model cause relation model Comment does not exist. "
. "Create the Comment Model by himself or run command 'php artisan make:entity Comment --only-model'.",
);

app(ModelGenerator::class)
->setModel('Post')
->setRelations([
'hasOne' => ['Comment'],
'hasMany' => [],
'belongsTo' => [],
'belongsToMany' => [],
])
->generate();
}

public function testCreateModel()
{
$this->mockFilesystem();

app(ModelGenerator::class)
->setModel('Post')
->setFields([
'integer-required' => ['media_id'],
'boolean-required' => ['is_published'],
])
->setRelations([
'hasOne' => ['Comment'],
'hasMany' => ['User'],
'belongsTo' => [],
'belongsToMany' => [],
])
->generate();

$this->assertGeneratedFileEquals('new_model.php', 'app/Models/Post.php');
$this->assertGeneratedFileEquals('comment_relation_model.php', 'app/Models/Comment.php');
$this->assertGeneratedFileEquals('comment_relation_model.php', 'app/Models/User.php');

$this->assertEventPushed(
className: SuccessCreateMessage::class,
message: 'Created a new Model: Post',
);
}

public function testCreateModelStubNotExist()
{
$this->mockFilesystem();

config(['entity-generator.stubs.model' => 'incorrect_stub']);

app(ModelGenerator::class)
->setModel('Post')
->setFields([])
->generate();

$this->assertFileDoesNotExist('app/Models/Post.php');
$this->assertFileDoesNotExist('app/Models/Comment.php');
$this->assertFileDoesNotExist('app/Models/User.php');

$this->assertEventPushed(
className: WarningEvent::class,
message: 'Generation of model has been skipped cause the view incorrect_stub from the config entity-generator.stubs.model is not exists. Please check that config has the correct view name value.',
);
}

public function testCreateModelWithoutRelationsRelationStubNotExist()
{
$this->mockFilesystem();

config(['entity-generator.stubs.relation' => 'incorrect_stub']);

app(ModelGenerator::class)
->setModel('Post')
->setFields([])
->generate();

$this->assertGeneratedFileEquals('new_model_without_fields_and_relations.php', 'app/Models/Post.php');

$this->assertEventPushed(
className: SuccessCreateMessage::class,
message: 'Created a new Model: Post',
);
}

public function testCreateModelWithRelationsRelationStubNotExist()
{
$this->mockFilesystem();

config(['entity-generator.stubs.relation' => 'incorrect_stub']);

app(ModelGenerator::class)
->setModel('Post')
->setFields([])
->setRelations([
'hasOne' => ['Comment'],
'hasMany' => ['User'],
'belongsTo' => [],
'belongsToMany' => [],
])
->generate();

$this->assertFileDoesNotExist('new_model.php', 'app/Models/Post.php');

$this->assertEventPushed(
className: WarningEvent::class,
message: 'Generation of model has been skipped cause the view incorrect_stub from the config entity-generator.stubs.relation is not exists. Please check that config has the correct view name value.',
);
}
}
8 changes: 0 additions & 8 deletions tests/NovaResourceGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace RonasIT\Support\Tests;

use Illuminate\Support\Facades\Event;
use RonasIT\Support\Events\SuccessCreateMessage;
use RonasIT\Support\Events\WarningEvent;
use RonasIT\Support\Exceptions\ClassAlreadyExistsException;
Expand All @@ -14,13 +13,6 @@ class NovaResourceGeneratorTest extends TestCase
{
use NovaResourceGeneratorMockTrait;

public function setUp(): void
{
parent::setUp();

Event::fake();
}

public function testCreateWithMissingNovaPackage()
{
$this->mockNovaServiceProviderExists(false);
Expand Down
7 changes: 0 additions & 7 deletions tests/NovaTestGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace RonasIT\Support\Tests;

use RonasIT\Support\Tests\Support\Models\WelcomeBonus;
use Illuminate\Support\Facades\Event;
use RonasIT\Support\Events\SuccessCreateMessage;
use RonasIT\Support\Events\WarningEvent;
use RonasIT\Support\Exceptions\ClassAlreadyExistsException;
Expand Down Expand Up @@ -58,8 +57,6 @@ className: ClassAlreadyExistsException::class,

public function testNovaTestStubNotExist()
{
Event::fake();

$this->mockNativeGeneratorFunctions(
$this->nativeClassExistsMethodCall([NovaServiceProvider::class, true]),
$this->nativeClassExistsMethodCall([WelcomeBonus::class, true]),
Expand Down Expand Up @@ -96,8 +93,6 @@ className: WarningEvent::class,

public function testDumpStubNotExist()
{
Event::fake();

$this->mockNovaServiceProviderExists();

$this->mockFilesystem();
Expand Down Expand Up @@ -156,8 +151,6 @@ public function testSuccess()

public function testGenerateNovaPackageNotInstall()
{
Event::fake();

$this->mockNovaServiceProviderExists(false);

app(NovaTestGenerator::class)
Expand Down
Loading
Loading