Skip to content

Commit

Permalink
allow a when callback to dictate retries
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed Jun 15, 2019
1 parent 6a18e73 commit 85c0801
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/Illuminate/Support/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -800,11 +800,12 @@ function preg_replace_array($pattern, array $replacements, $subject)
* @param int $times
* @param callable $callback
* @param int $sleep
* @param callable $when
* @return mixed
*
* @throws \Exception
*/
function retry($times, callable $callback, $sleep = 0)
function retry($times, callable $callback, $sleep = 0, $when = null)
{
$attempts = 0;
$times--;
Expand All @@ -815,7 +816,7 @@ function retry($times, callable $callback, $sleep = 0)
try {
return $callback($attempts);
} catch (Exception $e) {
if (! $times) {
if (! $times || ($when && ! $when($e))) {
throw $e;
}

Expand Down
36 changes: 36 additions & 0 deletions tests/Support/SupportHelpersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,42 @@ public function testRetry()
$this->assertTrue(microtime(true) - $startTime >= 0.1);
}

public function testRetryWithPassingWhenCallback()
{
$startTime = microtime(true);

$attempts = retry(2, function ($attempts) {
if ($attempts > 1) {
return $attempts;
}

throw new RuntimeException;
}, 100, function ($ex) {
return true;
});

// Make sure we made two attempts
$this->assertEquals(2, $attempts);

// Make sure we waited 100ms for the first attempt
$this->assertTrue(microtime(true) - $startTime >= 0.1);
}

public function testRetryWithFailingWhenCallback()
{
$this->expectException(RuntimeException::class);

$attempts = retry(2, function ($attempts) {
if ($attempts > 1) {
return $attempts;
}

throw new RuntimeException;
}, 100, function ($ex) {
return false;
});
}

public function testTransform()
{
$this->assertEquals(10, transform(5, function ($value) {
Expand Down

0 comments on commit 85c0801

Please sign in to comment.