Skip to content

Commit

Permalink
Ensure enum type is used in factory (#724)
Browse files Browse the repository at this point in the history
  • Loading branch information
benjam-es authored Dec 30, 2024
1 parent e4a7397 commit f35f399
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Generators/FactoryGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ protected function buildDefinition(Model $model): string
$definition .= sprintf('%s::factory()', $class);
$definition .= ',' . PHP_EOL;
} elseif (in_array($column->dataType(), ['enum', 'set']) && !empty($column->attributes())) {
$faker = FakerRegistry::fakerData($column->name()) ?? FakerRegistry::fakerDataType($column->dataType());
$faker = FakerRegistry::fakerDataType($column->dataType()) ?? FakerRegistry::fakerData($column->name());
$definition .= str_repeat(self::INDENT, 3) . "'{$column->name()}' => ";
$definition .= '$this->faker->' . $faker;
$definition .= ',' . PHP_EOL;
Expand Down
20 changes: 20 additions & 0 deletions tests/Feature/Generators/FactoryGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,26 @@ public function output_creates_directory_for_nested_components(): void
$this->assertEquals(['created' => ['database/factories/Admin/UserFactory.php']], $this->subject->output($tree));
}

#[Test]
public function output_factory_uses_enum(): void
{
$this->filesystem->expects('stub')
->with($this->factoryStub)
->andReturn($this->stub($this->factoryStub));

$this->filesystem->expects('exists')
->with('database/factories')
->andReturnTrue();

$this->filesystem->expects('put')
->with('database/factories/PostFactory.php', $this->fixture('factories/with-enum.php'));

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

$this->assertEquals(['created' => ['database/factories/PostFactory.php']], $this->subject->output($tree));
}

public static function modelTreeDataProvider(): array
{
return [
Expand Down
3 changes: 3 additions & 0 deletions tests/fixtures/drafts/with-enum.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
models:
Post:
name: enum:one,two,three
27 changes: 27 additions & 0 deletions tests/fixtures/factories/with-enum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
use App\Models\Post;

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

/**
* Define the model's default state.
*/
public function definition(): array
{
return [
'name' => $this->faker->randomElement(["one","two","three"]),
];
}
}

0 comments on commit f35f399

Please sign in to comment.