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
609 stars 63 forks source link

Add Faker `optional()` by default for nullable fields #536

Open MrYamous opened 6 months ago

MrYamous commented 6 months ago

When using make:factory --all-fields Foundry generate default values for all fields according to their type. WDYT about adding optional() method from Faker by default for those values ?

For example if i have an entity with a nullable field phone currently the default generated is :

'phone' => self::faker()->text(),

My proposal would be to have :

'phone' => self::faker()->optional()->text(),

nikophil commented 6 months ago

Hi @MrYamous

This sounds good! I assume you'd want that only for nullable properties?

MrYamous commented 6 months ago

Hi @MrYamous

This sounds good! I assume you'd want that only for nullable properties?

Hi,

Yes only for nullable properties IIUC it will be when --all-fields flag is added as this option is for generate default for nullable too

nikophil commented 6 months ago

you're absolutely right!

are you willing to provide a PR?

MrYamous commented 6 months ago

Yes i'll work on it

MrYamous commented 6 months ago

I've started looking how to do it but I'm not sure I'm going in the right direction.

To start with DoctrineScalarFieldsDefaultPropertiesGuesser i think I have to add in const DEFAULTS a way to know if ->optional() should be added, for a string it could be 'STRING' => 'self::faker(){optional}->text({length}),' And then use str_replace to add optional method from Faker or just let the default value

nikophil commented 6 months ago

maybe str_replace() on {faker}->text({length})?

In this class you can know if the field is nullable from doctrine's metadata

be careful, you'd need to modify ObjectDefaultPropertiesGuesser as well