spatie/test-time – A PHP package to control the flow of time

Freek has created spatie/test-time, a package to easily freeze/rewind/advance time in PHP.

Imagine you’re building that your app can notify your user, but you don’t want to send more than one notification in a timeframe of five seconds. How are you going to test the time aspect? Do you have to create a test that takes five minutes?

Luckily the answer is “no”. If you’re using the popular Carbon library, you can set the value that the library considers “now”

The package provides a few convenience methods around Carbon’s setTestNow method:

// time will not progress anymore
TestTime::freeze();

// Advance one minute
TestTime::addMinute();

// Rewind 5 hours
TestTime::subHours(5);

💁‍♂️ If you are not using Carbon you can reside to the php-timecop PHP extension that does the job (and affects \DateTime).

A PHP package to control the flow of time →
spatie/test-time (GitHub) →

php-timecop – A PHP extension providing “time travel” capabilities

Now this looks handy, especially when you’re writing/testing code that’s dependent on the system’s time:

php-timecop is a PHP extension providing “time travel” and “time freezing” capabilities

  • Freeze time to a specific point.
  • Travel back to a specific point in time, but allow time to continue moving forward from there.
  • Scale time by a given scaling factor that will cause time to move at an accelerated pace.
  • Override time-related PHP stock functions and methods, which supports freezing or traveling time.
var_dump(date("Y-m-d")); // todays date
timecop_freeze(0);
var_dump(gmdate("Y-m-d H:i:s")); // string(19) "1970-01-01 00:00:00"
var_dump(strtotime("+100000 sec")); // int(100000)

php-timecop
Stub PHP date() and the crew with php-timecop