foundry icon indicating copy to clipboard operation
foundry copied to clipboard

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

Open MrYamous opened this issue 1 year ago • 6 comments

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(),

MrYamous avatar Dec 06 '23 14:12 MrYamous

Hi @MrYamous

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

nikophil avatar Dec 06 '23 16:12 nikophil

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

MrYamous avatar Dec 06 '23 16:12 MrYamous

you're absolutely right!

are you willing to provide a PR?

nikophil avatar Dec 06 '23 18:12 nikophil

Yes i'll work on it

MrYamous avatar Dec 07 '23 06:12 MrYamous

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

MrYamous avatar Dec 10 '23 14:12 MrYamous

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

nikophil avatar Dec 11 '23 18:12 nikophil