Last active
March 14, 2018 16:19
-
-
Save pierre-dargham/b9285ea6500e0d24904e6d74c8ba0f80 to your computer and use it in GitHub Desktop.
try / retry (WP)
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 | |
namespace Globalis\WP\Retry; | |
// @todo: | |
// 1. POO style | |
// 2. if last try, and fail -> do_action | |
// 3. if last try : try / catch exception ? if $on_exception : throws exception ? | |
add_action('event_retry', __NAMESPACE . '\\_try', 10, 7); | |
function _try($callable, $args = [], $delay = 5, $retries = 1, $validator = 'validator_default', $use_cron = false, $on_exception = false) | |
{ | |
if(!is_array($args)) { | |
$args = [$args]; | |
} | |
if($retries < 1) { | |
return call_user_func_array($callable, $args); | |
} else { | |
$retries--; | |
} | |
$must_retry = false; | |
if($on_exception) | |
try { | |
$value = call_user_func_array($callable, $args); | |
} catch (Exception $e) { | |
$must_retry = true; | |
} | |
} else { | |
$value = call_user_func_array($callable, $args); | |
} | |
if($must_retry || !valid_return($value, $validator)) { | |
if($use_cron) { | |
$time = time() + $delay; | |
wp_schedule_single_event($time, 'event_retry', [$callable, $args, $delay, $retries, $validator, $cron, $on_exception]); | |
} else { | |
sleep($delay); | |
return _try($callable, $args, $delay, $retries, $validator, $cron, $on_exception) | |
} | |
} else { | |
return $value; | |
} | |
} | |
function valid_return($value, $validator) | |
{ | |
call_user_func($validator, $value); | |
} | |
function validator_default($value) | |
{ | |
return false !== $value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment