zenstruck / foundry

A model factory library for creating expressive, auto-completable, on-demand dev/test fixtures with Symfony and Doctrine.
https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html
MIT License
611 stars 63 forks source link

Question: Access pool from it's own story::build() #505

Closed jorismak closed 9 months ago

jorismak commented 9 months ago

Hi,

In a Story's build method, I start by creating a set of objects and add them in a pool.

Later in that story I want to get a random object from that pool. I find that this gets stuck in an infinite loop until PHP probably exists with memory-limits or stack-limits.

I think from quickly clicking through the code, that if I do self::getRandom('poolname') from within a Storys build method(), eventually Foundry tries to access the pool by doing static::load()->pools['poolname']. But I guess that load() thinks the Story is not loaded yet, and will call my Story's build() method again, which tries to access the pool, which acess my Story's build() method again, ....

Is it possible to get a random object from your own pool? If not, what would be a good method then? use faker()->randomElement($objects) to access a random one?

nikophil commented 9 months ago

Hi!

indeed when self::getRandom('poolname') is called, it call under the hood Story::load(). And if it was initially called in Story::load() itself, it results in an infinite loop.

This could be easily fixed, I've done it in this PR: https://github.com/zenstruck/foundry/pull/506

While waiting this to be released, you can indeed use faker