fzaninotto / Faker

Faker is a PHP library that generates fake data for you
MIT License
26.79k stars 3.59k forks source link

Suggestion - Faker method to randomly execute #2046

Open pnoeric opened 4 years ago

pnoeric commented 4 years ago

I'm using Faker with Laravel to populate a field that 70% of the time should have a random date, and the rest of the time it should be null. Here's how I do it now:

// 70% of the time set a date, otherwise it's null
'LastNudgeEmail' => (mt_rand(1, 10) > 3) ? $faker->dateTimeBetween("now", "+1 month") : null

I was thinking that it'd be cool if Faker had a new chainable method that would only pass along the chain if a % threshold was met; if it didn't pass, Faker would just return the value specified in the method call. So the above code could become a little more elegant and readable:

// 70% of the time set a date, otherwise it's null
'LastNudgeEmail' => $faker->chanceOfPassing(70, null)->dateTimeBetween("now", "+1 month")

(There's probably even a more elegant name/way to set up the method and its parameters... but you get the drift...)

patrickdaze commented 4 years ago

Maybe the optional() modifier?

'LastNudgeEmail' => $faker->optional(70)->dateTimeBetween('now', '+1 month')

Source code for optional()