Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
25 changes: 21 additions & 4 deletions src/Tempest/Framework/Testing/ModelFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Tempest\Framework\Testing;

use Tempest\Database\PrimaryKey;
use Tempest\Reflection\PropertyReflector;

use function Tempest\Mapper\map;
Expand Down Expand Up @@ -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;
}
Expand All @@ -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,
Expand Down
23 changes: 23 additions & 0 deletions tests/Integration/Testing/ModelFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Loading