Skip to content

Commit 85c0801

Browse files
committed
allow a when callback to dictate retries
1 parent 6a18e73 commit 85c0801

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

src/Illuminate/Support/helpers.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -800,11 +800,12 @@ function preg_replace_array($pattern, array $replacements, $subject)
800800
* @param int $times
801801
* @param callable $callback
802802
* @param int $sleep
803+
* @param callable $when
803804
* @return mixed
804805
*
805806
* @throws \Exception
806807
*/
807-
function retry($times, callable $callback, $sleep = 0)
808+
function retry($times, callable $callback, $sleep = 0, $when = null)
808809
{
809810
$attempts = 0;
810811
$times--;
@@ -815,7 +816,7 @@ function retry($times, callable $callback, $sleep = 0)
815816
try {
816817
return $callback($attempts);
817818
} catch (Exception $e) {
818-
if (! $times) {
819+
if (! $times || ($when && ! $when($e))) {
819820
throw $e;
820821
}
821822

tests/Support/SupportHelpersTest.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,42 @@ public function testRetry()
494494
$this->assertTrue(microtime(true) - $startTime >= 0.1);
495495
}
496496

497+
public function testRetryWithPassingWhenCallback()
498+
{
499+
$startTime = microtime(true);
500+
501+
$attempts = retry(2, function ($attempts) {
502+
if ($attempts > 1) {
503+
return $attempts;
504+
}
505+
506+
throw new RuntimeException;
507+
}, 100, function ($ex) {
508+
return true;
509+
});
510+
511+
// Make sure we made two attempts
512+
$this->assertEquals(2, $attempts);
513+
514+
// Make sure we waited 100ms for the first attempt
515+
$this->assertTrue(microtime(true) - $startTime >= 0.1);
516+
}
517+
518+
public function testRetryWithFailingWhenCallback()
519+
{
520+
$this->expectException(RuntimeException::class);
521+
522+
$attempts = retry(2, function ($attempts) {
523+
if ($attempts > 1) {
524+
return $attempts;
525+
}
526+
527+
throw new RuntimeException;
528+
}, 100, function ($ex) {
529+
return false;
530+
});
531+
}
532+
497533
public function testTransform()
498534
{
499535
$this->assertEquals(10, transform(5, function ($value) {

0 commit comments

Comments
 (0)