Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[10.x] Add Conditional Sleeps #47114

Merged
merged 5 commits into from
May 17, 2023
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: 24 additions & 0 deletions src/Illuminate/Support/Sleep.php
Original file line number Diff line number Diff line change
Expand Up @@ -411,4 +411,28 @@ protected function shouldNotSleep()

return $this;
}

/**
* Only sleep when the given condition is true.
*
* @param (\Closure($this): bool)|bool $condition
* @return $this
*/
public function when($condition)
{
$this->shouldSleep = (bool) value($condition, $this);

return $this;
}

/**
* Don't sleep when the given condition is true.
*
* @param (\Closure($this): bool)|bool $condition
* @return $this
*/
public function unless($condition)
{
return $this->when(! value($condition, $this));
}
}
38 changes: 38 additions & 0 deletions tests/Support/SleepTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -463,4 +463,42 @@ public function testItCanReplacePreviouslyDefinedDurations()
$sleep->setDuration(500)->milliseconds();
$this->assertSame($sleep->duration->totalMicroseconds, 500000);
}

public function testItCanSleepConditionallyWhen()
{
Sleep::fake();

// Control test
Sleep::assertSlept(fn () => true, 0);
Sleep::for(1)->second();
Sleep::assertSlept(fn () => true, 1);
Sleep::fake();
Sleep::assertSlept(fn () => true, 0);

// Reset
Sleep::fake();

// Will not sleep if `when()` yields `false`
Sleep::for(1)->second()->when(false);
Sleep::for(1)->second()->when(fn () => false);

// Will not sleep if `unless()` yields `true`
Sleep::for(1)->second()->unless(true);
Sleep::for(1)->second()->unless(fn () => true);

// Finish 'do not sleep' tests - assert no sleeping occurred
Sleep::assertSlept(fn () => true, 0);

// Will sleep if `when()` yields `true`
Sleep::for(1)->second()->when(true);
Sleep::assertSlept(fn () => true, 1);
Sleep::for(1)->second()->when(fn () => true);
Sleep::assertSlept(fn () => true, 2);

// Will sleep if `unless()` yields `false`
Sleep::for(1)->second()->unless(false);
Sleep::assertSlept(fn () => true, 3);
Sleep::for(1)->second()->unless(fn () => false);
Sleep::assertSlept(fn () => true, 4);
}
}