Skip to content

Commit fce3610

Browse files
committed
[minor] throw helpful exception if creating service factories w/o boot
1 parent a904e41 commit fce3610

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/ModelFactory.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,12 @@ final public static function new($defaultAttributes = [], string ...$states): se
2323
$defaultAttributes = [];
2424
}
2525

26-
$factory = self::isBooted() ? self::configuration()->factories()->create(static::class) : new static();
26+
try {
27+
$factory = self::isBooted() ? self::configuration()->factories()->create(static::class) : new static();
28+
} catch (\ArgumentCountError $e) {
29+
throw new \RuntimeException('Model Factories with dependencies (Model Factory services) cannot be created before foundry is booted.', 0, $e);
30+
}
31+
2732
$factory = $factory
2833
->withAttributes([$factory, 'getDefaults'])
2934
->withAttributes($defaultAttributes)

tests/Functional/ModelFactoryServiceTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Zenstruck\Foundry\Tests\Functional;
44

55
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
6+
use Zenstruck\Foundry\Factory;
67
use Zenstruck\Foundry\Test\Factories;
78
use Zenstruck\Foundry\Test\ResetDatabase;
89
use Zenstruck\Foundry\Tests\Fixtures\Factories\CategoryServiceFactory;
@@ -55,4 +56,17 @@ public function service_factories_cannot_be_used_without_bundle(): void
5556

5657
CategoryServiceFactory::new();
5758
}
59+
60+
/**
61+
* @test
62+
*/
63+
public function cannot_create_service_factories_without_foundry_booted(): void
64+
{
65+
Factory::shutdown();
66+
67+
$this->expectException(\RuntimeException::class);
68+
$this->expectExceptionMessage('Model Factories with dependencies (Model Factory services) cannot be created before foundry is booted.');
69+
70+
CategoryServiceFactory::new();
71+
}
5872
}

0 commit comments

Comments
 (0)