Created
April 4, 2019 11:23
-
-
Save vanderlee/0023903911647cb59b3d4ca5399dcf37 to your computer and use it in GitHub Desktop.
Try a callable a number of times
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Try a callable a number of times. | |
* If all attempts fail, handle a catch and/or finally. | |
* If no catch is provided, just throw the exception from the last failed attempt. | |
* If an attempt succeeds, return the number of attempts (at least one). | |
* If the provided number of attempts is zero or less, the code won't attempt to run at all. | |
* | |
* This is a quick hack, which can easily be improved and most likely still has issues. | |
*/ | |
function retry($attempts, callable $try, callable $catch = null, callable $finally = null) { | |
$attempt = 1; | |
while ($attempt <= $attempts) { | |
try { | |
$try(); | |
} catch (Throwable $throwable) { | |
$attempt++; | |
if ($attempt > $attempts) { | |
$catch && $catch($throwable); | |
$finally && $finally(); | |
if (!$catch) { | |
throw $throwable; | |
} | |
return false; | |
} | |
} | |
} | |
$finally && $finally(); | |
return $attempt; | |
} | |
$a = 0; | |
retry(3, function() use (&$a) { | |
++$a; | |
throw new Exception('foobar:' . $a); | |
}, function(Throwable $e) { | |
var_dump($e); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment