diff --git a/src/Tempest/Framework/Testing/ModelFactory.php b/src/Tempest/Framework/Testing/ModelFactory.php index 285504a48..ded7795c2 100644 --- a/src/Tempest/Framework/Testing/ModelFactory.php +++ b/src/Tempest/Framework/Testing/ModelFactory.php @@ -2,6 +2,7 @@ namespace Tempest\Framework\Testing; +use Tempest\Database\PrimaryKey; use Tempest\Reflection\PropertyReflector; use function Tempest\Mapper\map; @@ -75,14 +76,14 @@ public function make() continue; } - if ($property->isNullable()) { + $value = $this->generateValue($property); + + if ($value === null && $property->isNullable()) { $property->setValue($model, null); continue; } - $value = $this->generateValue($property); - if ($value === null) { continue; } @@ -109,7 +110,23 @@ public function save() private function generateValue(PropertyReflector $property): mixed { - return match ($property->getType()->getName()) { + $type = $property->getType(); + + if ($type->matches(PrimaryKey::class)) { + return null; + } + + if ($type->isEnum()) { + $cases = arr($type->getName()::cases()); + + return $cases->random(); + } + + if ($type->isClass()) { + return new self($type->getName())->make(); + } + + return match ($type->getName()) { 'string' => arr(['Lorem', 'Ipsum', 'Dolor', 'Sit', 'Amet'])->random(), 'int' => random_int(1, 100), 'float' => random_int(100, 1000) / 10, diff --git a/tests/Integration/Testing/ModelFactoryTest.php b/tests/Integration/Testing/ModelFactoryTest.php index ff4d35088..7ac47fc33 100644 --- a/tests/Integration/Testing/ModelFactoryTest.php +++ b/tests/Integration/Testing/ModelFactoryTest.php @@ -8,7 +8,9 @@ use Tests\Tempest\Fixtures\Migrations\CreateBookTable; use Tests\Tempest\Fixtures\Migrations\CreatePublishersTable; use Tests\Tempest\Fixtures\Modules\Books\Models\Author; +use Tests\Tempest\Fixtures\Modules\Books\Models\AuthorType; use Tests\Tempest\Fixtures\Modules\Books\Models\Book; +use Tests\Tempest\Fixtures\Modules\Books\Models\Isbn; use Tests\Tempest\Integration\FrameworkIntegrationTestCase; use function Tempest\Framework\Testing\factory; @@ -152,4 +154,25 @@ public function test_items_save_to_the_database(): void $this->database->assertTableHasRow('books', id: $a->id, title: $a->title); $this->database->assertTableHasRow('books', id: $b->id, title: $b->title); } + + #[Test] + public function test_make_with_nested_object(): void + { + $isbn = factory(Isbn::class)->make(); + + $this->assertInstanceOf(Book::class, $isbn->book); + } + + #[Test] + public function test_make_with_enum(): void + { + $author = factory(AuthorWithEnum::class)->make(); + + $this->assertInstanceOf(AuthorType::class, $author->type); + } +} + +class AuthorWithEnum +{ + public AuthorType $type; }