php-quickcheck icon indicating copy to clipboard operation
php-quickcheck copied to clipboard

Generate DateTime objects?

Open letharion opened this issue 3 years ago • 5 comments

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);
            }
        );
    }
}

letharion avatar Mar 11 '21 18:03 letharion

You should default to creating DateTimeImmutable objects.

djmattyg007 avatar Mar 11 '21 20:03 djmattyg007

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 DateTimes specifically.

letharion avatar Mar 13 '21 20:03 letharion

Are you able to share the name of the library you're dealing with?

djmattyg007 avatar Mar 14 '21 00:03 djmattyg007

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.

letharion avatar Mar 14 '21 08:03 letharion

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.

drupol avatar Jun 10 '22 12:06 drupol