Skip to content
Permalink
Browse files

allow a when callback to dictate retries

  • Loading branch information...
taylorotwell committed Jun 15, 2019
1 parent 6a18e73 commit 85c08016c424f6c8e45f08282523f8785eda9673
Showing with 39 additions and 2 deletions.
  1. +3 −2 src/Illuminate/Support/helpers.php
  2. +36 −0 tests/Support/SupportHelpersTest.php
@@ -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--;
@@ -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;
}
@@ -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) {

0 comments on commit 85c0801

Please sign in to comment.
You can’t perform that action at this time.