Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion src/Illuminate/Support/Sleep.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

namespace Illuminate\Support;

use Carbon\Carbon;
use Carbon\CarbonInterval;
use DateInterval;
use Illuminate\Support\Carbon;
use Illuminate\Support\Traits\Macroable;
use PHPUnit\Framework\Assert as PHPUnit;
use RuntimeException;
Expand All @@ -20,6 +20,13 @@ class Sleep
*/
public static $fakeSleepCallbacks = [];

/**
* Keep Carbon's "now" in sync when sleeping.
*
* @var bool
*/
protected static $syncWithCarbon = false;

/**
* The total duration to sleep.
*
Expand Down Expand Up @@ -259,6 +266,10 @@ public function __destruct()
if (static::$fake) {
static::$sequence[] = $this->duration;

if (static::$syncWithCarbon) {
Carbon::setTestNow(Carbon::now()->add($this->duration));
}

foreach (static::$fakeSleepCallbacks as $callback) {
$callback($this->duration);
}
Expand Down Expand Up @@ -317,6 +328,7 @@ public static function fake($value = true)

static::$sequence = [];
static::$fakeSleepCallbacks = [];
static::$syncWithCarbon = false;
}

/**
Expand Down Expand Up @@ -458,4 +470,14 @@ public static function whenFakingSleep($callback)
{
static::$fakeSleepCallbacks[] = $callback;
}

/**
* Indicate that Carbon's "now" should be kept in sync when sleeping.
*
* @return void
*/
public static function syncWithCarbon($value = true)
{
static::$syncWithCarbon = $value;
}
}
30 changes: 30 additions & 0 deletions tests/Support/SleepTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Carbon\CarbonInterval;
use Exception;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Sleep;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -563,4 +564,33 @@ public function testItDoesntRunCallbacksWhenNotFaking()

$this->assertTrue(true);
}

public function testItDoesNotSyncCarbon()
{
Carbon::setTestNow('2000-01-01 00:00:00');
Sleep::fake();

Sleep::for(5)->minutes()
->and(3)->seconds();

Sleep::assertSequence([
Sleep::for(303)->seconds(),
]);
$this->assertSame('2000-01-01 00:00:00', Date::now()->toDateTimeString());
}

public function testItCanSyncCarbon()
{
Carbon::setTestNow('2000-01-01 00:00:00');
Sleep::fake();
Sleep::syncWithCarbon();

Sleep::for(5)->minutes()
->and(3)->seconds();

Sleep::assertSequence([
Sleep::for(303)->seconds(),
]);
$this->assertSame('2000-01-01 00:05:03', Date::now()->toDateTimeString());
}
}