Skip to content
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
474d057
test: add tests for factory generator.
Dec 18, 2023
0783b7c
Merge branch 'master' into 49-add-tests
Dec 19, 2023
a4d14e2
test: add factory generator tests.
Dec 20, 2023
90e983c
test: add tests for factory generator.
Dec 20, 2023
c3baf27
Merge branch '49-add-tests' into 49-add-factory-tests
Dec 20, 2023
32b1803
Merge branch 'master' into 49-add-factory-tests
Jan 17, 2024
798038d
Merge branch 'master' into 49-add-factory-tests
t0xas Nov 19, 2024
485b59f
chore: add factory tests
t0xas Nov 20, 2024
91e584b
chore: add factory tests
t0xas Nov 20, 2024
ea69440
chore: add factory tests
t0xas Nov 20, 2024
35d51f7
chore: add factory tests
t0xas Nov 20, 2024
67fd5fb
chore: add factory tests
t0xas Nov 20, 2024
a9f3ca2
chore: add factory tests
t0xas Nov 20, 2024
672aaef
chore: add factory tests
t0xas Nov 20, 2024
04dfc78
chore: add factory tests
t0xas Nov 20, 2024
0e1496b
feat: remove useless code
pirs1337 Nov 27, 2024
7aa73ba
feat: remove useless code
pirs1337 Nov 27, 2024
bbce08b
refactor: remove useless classes
pirs1337 Nov 27, 2024
0718d41
refactor: code
pirs1337 Nov 28, 2024
5188958
refactor: code
pirs1337 Nov 28, 2024
fac9425
refactor: code
pirs1337 Nov 28, 2024
fdb25c8
refactor: remove useless stubs
pirs1337 Nov 29, 2024
f6fa94c
Update tests/Support/Factory/FactoryMockTrait.php
DenTray Dec 2, 2024
171ab25
Merge remote-tracking branch 'origin/master' into 49-add-factory-tests
pirs1337 Dec 2, 2024
53f9fce
fix: conflicts
pirs1337 Dec 2, 2024
875c2fd
Merge remote-tracking branch 'origin/49-add-factory-tests' into 49-ad…
pirs1337 Dec 2, 2024
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
9 changes: 9 additions & 0 deletions src/Exceptions/FakerMethodNotFound.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace RonasIT\Support\Exceptions;

use Exception;

class FakerMethodNotFound extends Exception
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
class FakerMethodNotFound extends Exception
class FakerMethodNotFoundException extends Exception

{
}
95 changes: 54 additions & 41 deletions src/Generators/FactoryGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@
use Faker\Generator as Faker;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use InvalidArgumentException;
use RonasIT\Support\Exceptions\FakerMethodNotFound;
use RonasIT\Support\Exceptions\ModelFactoryNotFound;
use RonasIT\Support\Exceptions\ClassNotExistsException;
use RonasIT\Support\Exceptions\ModelFactoryNotFoundedException;
use RonasIT\Support\Exceptions\ClassAlreadyExistsException;
use RonasIT\Support\Events\SuccessCreateMessage;
use Exception;

class FactoryGenerator extends EntityGenerator
{
Expand All @@ -26,21 +27,30 @@ class FactoryGenerator extends EntityGenerator
'json' => '[]',
];

public function generate(): void
{
$createMessage = ($this->allowedToCreateFactoryInSeparateClass())
? $this->generateSeparateClass()
: $this->generateToGenericClass();

event(new SuccessCreateMessage($createMessage));
}

protected function generateSeparateClass(): string
{
if (!$this->classExists('models', $this->model)) {
$this->throwFailureException(
ClassNotExistsException::class,
"Cannot create {$this->model}Factory cause {$this->model} Model does not exists.",
"Create a {$this->model} Model by himself or run command 'php artisan make:entity {$this->model} --only-model'."
exceptionClass: ClassNotExistsException::class,
failureMessage: "Cannot create {$this->model}Factory cause {$this->model} Model does not exists.",
recommendedMessage: "Create a {$this->model} Model by itself or run command 'php artisan make:entity {$this->model} --only-model'."
);
}

if ($this->classExists('factory', "{$this->model}Factory")) {
$this->throwFailureException(
ClassAlreadyExistsException::class,
"Cannot create {$this->model}Factory cause {$this->model}Factory already exists.",
"Remove {$this->model}Factory."
exceptionClass: ClassAlreadyExistsException::class,
failureMessage: "Cannot create {$this->model}Factory cause {$this->model}Factory already exists.",
recommendedMessage: "Remove {$this->model}Factory."
);
}

Expand Down Expand Up @@ -74,7 +84,7 @@ protected function generateToGenericClass(): string

$createMessage = "Created a new Test factory for {$this->model} model in '{$this->paths['factory']}'";

file_put_contents($this->paths['factory'], $content, FILE_APPEND);
file_put_contents(base_path($this->paths['factory']), $content, FILE_APPEND);

$this->prepareRelatedFactories();
} else {
Expand All @@ -84,13 +94,9 @@ protected function generateToGenericClass(): string
return $createMessage;
}

public function generate(): void
protected function allowedToCreateFactoryInSeparateClass(): bool
Copy link
Collaborator

Choose a reason for hiding this comment

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

we can fully remove this logic as now package requires Laravel 11

{
$createMessage = (version_compare(app()->version(), '8', '>='))
? $this->generateSeparateClass()
: $this->generateToGenericClass();

event(new SuccessCreateMessage($createMessage));
return version_compare(app()->version(), '8', '>=');
}

protected function prepareEmptyFactory(): void
Expand All @@ -102,28 +108,31 @@ protected function prepareEmptyFactory(): void

list($basePath, $databaseFactoryDir) = extract_last_part(config('entity-generator.paths.factory'), '/');

$databaseFactoryDir = base_path($databaseFactoryDir);

if (!is_dir($databaseFactoryDir)) {
mkdir($databaseFactoryDir);
}

file_put_contents($this->paths['factory'], $content);
file_put_contents(base_path($this->paths['factory']), $content);
}

protected function checkExistRelatedModelsFactories(): bool
{
$modelFactoryContent = file_get_contents($this->paths['factory']);
$modelFactoryContent = file_get_contents(base_path($this->paths['factory']));
$relatedModels = $this->getRelatedModels($this->model);
$modelNamespace = $this->getOrCreateNamespace('models');

foreach ($relatedModels as $relatedModel) {
$relatedFactoryClass = "{$modelNamespace}\\$relatedModel::class";
$existModelFactory = strpos($modelFactoryContent, $relatedFactoryClass);
$existModelFactory = Str::contains($modelFactoryContent, $relatedFactoryClass);

if (!$existModelFactory) {
$this->throwFailureException(
ModelFactoryNotFoundedException::class,
"Not found $relatedModel factory for $relatedModel model in '{$this->paths['factory']}",
"Please declare a factory for $relatedModel model on '{$this->paths['factory']}' path and run your command with option '--only-tests'."
exceptionClass: ModelFactoryNotFoundedException::class,
failureMessage: "Not found {$relatedModel} factory for {$relatedModel} model in '{$this->paths['factory']}.",
recommendedMessage: "Please declare a factory for {$relatedModel} model on '{$this->paths['factory']}' "
. "path and run your command with option '--only-tests'."
);
}
}
Expand All @@ -146,25 +155,27 @@ protected static function getCustomMethod($field): string
return self::CUSTOM_METHODS[$field['type']];
}

$message = $field['type'] . 'not found in CUSTOM_METHODS variable CUSTOM_METHODS = ' . self::CUSTOM_METHODS;
throw new Exception($message);
$message = "Cannot generate fake data for unsupported {$field['type']} field type. "
. "Supported custom field types are " . implode(', ', array_keys(self::CUSTOM_METHODS));

throw new FakerMethodNotFound($message);
}

protected function prepareRelatedFactories(): void
{
$relations = array_merge(
$this->relations['hasOne'],
$this->relations['hasMany']
$this->relations['hasMany'],
);

foreach ($relations as $relation) {
$modelFactoryContent = file_get_contents($this->paths['factory']);
$modelFactoryContent = file_get_contents(base_path($this->paths['factory']));

if (!Str::contains($modelFactoryContent, $this->getModelClass($relation))) {
$this->throwFailureException(
ModelFactoryNotFound::class,
"Model factory for mode {$relation} not found.",
"Please create it and after thar you can run this command with flag '--only-tests'."
exceptionClass: ModelFactoryNotFound::class,
failureMessage: "Model factory for model {$relation} not found.",
recommendedMessage: "Please create it and after thar you can run this command with flag '--only-tests'."
);
}

Expand All @@ -180,7 +191,7 @@ protected function prepareRelatedFactories(): void
$modelFactoryContent = str_replace($match, $match . $newField, $modelFactoryContent);
}

file_put_contents($this->paths['factory'], $modelFactoryContent);
file_put_contents(base_path($this->paths['factory']), $modelFactoryContent);
}
}

Expand All @@ -193,24 +204,27 @@ public static function getFactoryFieldsContent($field): string
return 1;
}

if (property_exists($faker, $field['name'])) {
return "\$faker-\>{$field['name']}";
try {
$faker->{$field['name']};
$hasFormatter = true;
} catch (InvalidArgumentException $e) {
$hasFormatter = false;
}

if (method_exists($faker, $field['name'])) {
return "\$faker-\>{$field['name']}()";
if ($hasFormatter) {
return "\$faker->{$field['name']}";
}

return self::getFakerMethod($field);
}

protected function checkExistModelFactory(): int
protected function checkExistModelFactory(): bool
{
$modelFactoryContent = file_get_contents($this->paths['factory']);
$modelFactoryContent = file_get_contents(base_path($this->paths['factory']));
$modelNamespace = $this->getOrCreateNamespace('models');
$factoryClass = "{$modelNamespace}\\$this->model::class";

return strpos($modelFactoryContent, $factoryClass);
return Str::contains($modelFactoryContent, $factoryClass);
}

protected function prepareFields(): array
Expand All @@ -219,11 +233,9 @@ protected function prepareFields(): array

foreach ($this->fields as $type => $fields) {
foreach ($fields as $field) {
$explodedType = explode('-', $type);

$result[] = [
'name' => $field,
'type' => head($explodedType)
'type' => Str::before($type, '-'),
];
}
}
Expand Down Expand Up @@ -261,9 +273,10 @@ protected function getModelClassContent($model): string

if (!$this->classExists('models', $model)) {
$this->throwFailureException(
ClassNotExistsException::class,
"Cannot create {$model} Model cause {$model} Model does not exists.",
"Create a {$model} Model by himself or run command 'php artisan make:entity {$model} --only-model'."
exceptionClass: ClassNotExistsException::class,
failureMessage: "Cannot get {$model} Model class content cause {$model} Model does not exists.",
recommendedMessage: "Create a {$model} Model by itself or run command "
. "'php artisan make:entity {$model} --only-model'."
);
}

Expand Down
2 changes: 1 addition & 1 deletion stubs/factory.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ public function definition(): array
@endforeach
];
}
}
}
6 changes: 3 additions & 3 deletions tests/ControllerGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public function testControllerAlreadyExists()
$this->classExistsMethodCall(['controllers', 'PostController'])
]);

$this->assertExceptionThrowed(
$this->assertExceptionThrew(
className: ClassAlreadyExistsException::class,
message: 'Cannot create PostController cause PostController already exists. Remove PostController.',
);
Expand All @@ -44,7 +44,7 @@ public function testModelServiceNotExists()
$this->classExistsMethodCall(['services', 'PostService'], false)
]);

$this->assertExceptionThrowed(
$this->assertExceptionThrew(
className: ClassNotExistsException::class,
message: 'Cannot create PostService cause PostService does not exists. Create a PostService by himself.',
);
Expand All @@ -58,7 +58,7 @@ public function testRouteFileNotExists()
{
$this->mockFilesystemWithoutRoutesFile();

$this->assertExceptionThrowed(
$this->assertExceptionThrew(
className: FileNotFoundException::class,
message: "Not found file with routes. Create a routes file on path: 'vfs://root/routes/api.php'",
);
Expand Down
Loading
Loading