php-quickcheck
php-quickcheck copied to clipboard
Generate DateTime objects?
I quickly hacked up this to support testing my class that uses DateTime's extensively. Could it be of interest to others? The function can of course just be copy-pasted straight into the argument generation, but I figured this might help someone else. If only as an issue that be found through searching.
class GeneratorWithDates extends Gen
{
/**
* Generate DateTime objects
*
* @return Generator
*/
public static function dates($from = 1000, $to = 3000)
{
return self::choose($from, to)->map(
function ($i) {
return new DateTime($i);
}
);
}
}
You should default to creating DateTimeImmutable
objects.
I'd be happy to do so, if there's interesting in merging some code. In my particular use case though, I'm passing my dates on to a library which requires DateTime
s specifically.
Are you able to share the name of the library you're dealing with?
Sure, it's janephp. This discussion made me dig into the code though, and it looks like there's a config option for generating Immutable dates. I'm gonna give that a go.
I just stumbled upon this amazing library and this particular issue.
I'm working on a type generator here: https://github.com/loophp/typed-generators
It can generate any kind of typed value and shapes, while being completely understood by static analysis tools like PHPStan and PSalm.
Maybe this will help you.