Skip to content

Commit

Permalink
[10.x] Add Conditional Sleeps (#47114)
Browse files Browse the repository at this point in the history
* feat: add conditional methods to 'Sleep' class

* style: add dot at end of phpdoc lines

* formatting

* Update Sleep.php

* Update Sleep.php

---------

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
bradietilley and taylorotwell authored May 17, 2023
1 parent 053ad8b commit 1719c36
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
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);
}
}

0 comments on commit 1719c36

Please sign in to comment.