Skip to content

Commit 96de5cc

Browse files
committed
Provide retry callback with the attempt count
This provides the call back with a attempt count, this can be helpful for function that need to modify there behavior with each attempt, or log it some how.
1 parent 0431c06 commit 96de5cc

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/Illuminate/Support/helpers.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -739,19 +739,21 @@ function preg_replace_array($pattern, array $replacements, $subject)
739739
* Retry an operation a given number of times.
740740
*
741741
* @param int $times
742-
* @param callable $callback
742+
* @param callable $callback First parameter is the number of attempt
743743
* @param int $sleep
744744
* @return mixed
745745
*
746746
* @throws \Exception
747747
*/
748748
function retry($times, callable $callback, $sleep = 0)
749749
{
750+
$attempt = 0;
750751
$times--;
751752

752753
beginning:
754+
$attempt++;
753755
try {
754-
return $callback();
756+
return $callback($attempt);
755757
} catch (Exception $e) {
756758
if (! $times) {
757759
throw $e;

tests/Support/SupportHelpersTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -868,6 +868,25 @@ public function something()
868868
})->present()->something());
869869
}
870870

871+
public function testRetry()
872+
{
873+
$startTime = microtime(true);
874+
875+
$attempts = retry(2, function ($attempts) {
876+
if ($attempts > 1) {
877+
return $attempts;
878+
}
879+
880+
throw new RuntimeException;
881+
}, 100);
882+
883+
// Make sure we made two attempts
884+
$this->assertEquals(2, $attempts);
885+
886+
// Make sure we waited 100ms for the first attempt
887+
$this->assertTrue(microtime(true) - $startTime >= 0.1);
888+
}
889+
871890
public function testTransform()
872891
{
873892
$this->assertEquals(10, transform(5, function ($value) {

0 commit comments

Comments
 (0)