From 1719c366d18ebb01fcab77a2a78040fe5c7cded9 Mon Sep 17 00:00:00 2001 From: Bradie Tilley <44430471+bradietilley@users.noreply.github.com> Date: Wed, 17 May 2023 22:09:57 +0800 Subject: [PATCH] [10.x] Add Conditional Sleeps (#47114) * 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 --- src/Illuminate/Support/Sleep.php | 24 ++++++++++++++++++++ tests/Support/SleepTest.php | 38 ++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/src/Illuminate/Support/Sleep.php b/src/Illuminate/Support/Sleep.php index 101ed3b36f50..bb9022990870 100644 --- a/src/Illuminate/Support/Sleep.php +++ b/src/Illuminate/Support/Sleep.php @@ -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)); + } } diff --git a/tests/Support/SleepTest.php b/tests/Support/SleepTest.php index af73291014f1..48efdb506ebc 100644 --- a/tests/Support/SleepTest.php +++ b/tests/Support/SleepTest.php @@ -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); + } }