-
-
Notifications
You must be signed in to change notification settings - Fork 75
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Named FactoryCollection
constructors don't have proper type declarations
#609
Comments
One general problem with the So the factory class is technically known when a factory collection is created (because a factory instance is passed), but the information gets lost in the construction. Therefore, calls like $factories = MyFactory::new()->many();
foreach ($factories->all() as $factory) {
$factory->myMethodDefinedInMyFactoryClass();
} are not possible, because the moment we get the factory in the loop, it is just a general This could be changed if |
Hi @janopae sorry for the late reply.
This is actually true. In foundry v2, this is still the case. We have: /**
* @template T
* @implements \IteratorAggregate<Factory<T>>
*/
final class FactoryCollection implements \IteratorAggregate Maybe your solution would as well fix some problem with proxy/not-proxy objects in factory collection. I'm just wondering how we should document /**
* @return T[]
*/
public function create(array|callable $attributes = []): array Any thoughts, @kbond? By the way:
genuine question: do you really need to do this? I usually go for |
Thanks for taking the time to reply :)
I'd write it like this: /**
* @template TModel
* @template TFactory of Factory<TModel>
* @implements \IteratorAggregate<TFactory>
*/
final class FactoryCollection implements \IteratorAggregate
// ...
/**
* @return TModel[]
*/
public function create(array|callable $attributes = []): array
In my case, I needed some data that was all the same for all created objects, and some data that needed to be different. I wrote something like $factories = MyFactory::new()->setDataThatShouldBeTheSame()->many();
foreach ($factories->all() as $factory) {
$factory->dataThatShouldBeDifferent(faker()->randomElement($someDataToChooseFrom));
} If there's a more elegant way to do this, I'd love to switch to that. |
Ho yes, of course, double About |
The constructor of
FactoryCollection
has a@phpstan-param Factory<TObject> $factory
. Using this constructor is deprecated, and named constructors likeset
,range
etc. should be used instead. However, these named constructors are missing this annotation. Also, the annotation is only for PHPStorm, not for Psalm.This leads to Psalm errors like
The text was updated successfully, but these errors were encountered: