Skip to content

Commit f35f399

Browse files
authored
Ensure enum type is used in factory (#724)
1 parent e4a7397 commit f35f399

File tree

4 files changed

+51
-1
lines changed

4 files changed

+51
-1
lines changed

src/Generators/FactoryGenerator.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ protected function buildDefinition(Model $model): string
120120
$definition .= sprintf('%s::factory()', $class);
121121
$definition .= ',' . PHP_EOL;
122122
} elseif (in_array($column->dataType(), ['enum', 'set']) && !empty($column->attributes())) {
123-
$faker = FakerRegistry::fakerData($column->name()) ?? FakerRegistry::fakerDataType($column->dataType());
123+
$faker = FakerRegistry::fakerDataType($column->dataType()) ?? FakerRegistry::fakerData($column->name());
124124
$definition .= str_repeat(self::INDENT, 3) . "'{$column->name()}' => ";
125125
$definition .= '$this->faker->' . $faker;
126126
$definition .= ',' . PHP_EOL;

tests/Feature/Generators/FactoryGeneratorTest.php

+20
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,26 @@ public function output_creates_directory_for_nested_components(): void
166166
$this->assertEquals(['created' => ['database/factories/Admin/UserFactory.php']], $this->subject->output($tree));
167167
}
168168

169+
#[Test]
170+
public function output_factory_uses_enum(): void
171+
{
172+
$this->filesystem->expects('stub')
173+
->with($this->factoryStub)
174+
->andReturn($this->stub($this->factoryStub));
175+
176+
$this->filesystem->expects('exists')
177+
->with('database/factories')
178+
->andReturnTrue();
179+
180+
$this->filesystem->expects('put')
181+
->with('database/factories/PostFactory.php', $this->fixture('factories/with-enum.php'));
182+
183+
$tokens = $this->blueprint->parse($this->fixture('drafts/with-enum.yaml'));
184+
$tree = $this->blueprint->analyze($tokens);
185+
186+
$this->assertEquals(['created' => ['database/factories/PostFactory.php']], $this->subject->output($tree));
187+
}
188+
169189
public static function modelTreeDataProvider(): array
170190
{
171191
return [

tests/fixtures/drafts/with-enum.yaml

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
models:
2+
Post:
3+
name: enum:one,two,three
+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
namespace Database\Factories;
4+
5+
use Illuminate\Database\Eloquent\Factories\Factory;
6+
use Illuminate\Support\Str;
7+
use App\Models\Post;
8+
9+
class PostFactory extends Factory
10+
{
11+
/**
12+
* The name of the factory's corresponding model.
13+
*
14+
* @var string
15+
*/
16+
protected $model = Post::class;
17+
18+
/**
19+
* Define the model's default state.
20+
*/
21+
public function definition(): array
22+
{
23+
return [
24+
'name' => $this->faker->randomElement(["one","two","three"]),
25+
];
26+
}
27+
}

0 commit comments

Comments
 (0)