InteractsWithTime.php
TLDR
The InteractsWithTime
trait provides methods for manipulating the current time for testing purposes.
Methods
freezeTime
Freezes the current time. It takes an optional callback as a parameter that will be executed while the time is frozen.
freezeSecond
Freezes the current time at the beginning of the second. It takes an optional callback as a parameter that will be executed while the time is frozen.
travel
Begins traveling to another time. It takes the desired time (as an integer) as a parameter and returns a Wormhole
object.
travelTo
Travels to a specific time. It takes the desired time (as a DateTimeInterface
, Closure
, Carbon
instance, string, boolean, or null) and an optional callback as parameters. It sets the test now to the specified time. If a callback is provided, it will be executed while the time is set. Afterward, the test now is reset.
travelBack
Travels back to the current time. It returns a DateTimeInterface
object representing the current time.
<?php
namespace Illuminate\Foundation\Testing\Concerns;
use Illuminate\Foundation\Testing\Wormhole;
use Illuminate\Support\Carbon;
trait InteractsWithTime
{
/**
* Freeze time.
*
* @param callable|null $callback
* @return mixed
*/
public function freezeTime($callback = null)
{
return $this->travelTo(Carbon::now(), $callback);
}
/**
* Freeze time at the beginning of the current second.
*
* @param callable|null $callback
* @return mixed
*/
public function freezeSecond($callback = null)
{
return $this->travelTo(Carbon::now()->startOfSecond(), $callback);
}
/**
* Begin travelling to another time.
*
* @param int $value
* @return \Illuminate\Foundation\Testing\Wormhole
*/
public function travel($value)
{
return new Wormhole($value);
}
/**
* Travel to another time.
*
* @param \DateTimeInterface|\Closure|\Illuminate\Support\Carbon|string|bool|null $date
* @param callable|null $callback
* @return mixed
*/
public function travelTo($date, $callback = null)
{
Carbon::setTestNow($date);
if ($callback) {
return tap($callback($date), function () {
Carbon::setTestNow();
});
}
}
/**
* Travel back to the current time.
*
* @return \DateTimeInterface
*/
public function travelBack()
{
return Wormhole::back();
}
}