Skip to content

Commit

Permalink
Added capability to halt retries by returning false from exception ha…
Browse files Browse the repository at this point in the history
…ndler.
  • Loading branch information
Bilge committed Dec 7, 2016
1 parent 5e182e6 commit dfe63fb
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,17 @@ Requirements
Usage
-----

The `retry` function retries an operation up to the specified number of times with an optional error handler and has
the following signature.
The `retry` function retries an operation up to the specified number of times with an optional exception handler.

If an exception handler is specified, it is called immediately before retrying the operation. If the handler returns
`false`, the operation is not retried.

```
retry(int $times, callable $operation, callable $onError = null);
```
* `$times`—Maximum number of times the operation may run.
* `$operation`—Operation to run up to the specified number of times.
* `$onError`—Optional. Error handler called immediately before retrying the operation.
* `$onError`—Optional. Exception handler that receives the thrown exception as its first argument.

Note in the original library, `$times` specifies the number of *retries* and therefore the operation could run up to
`$times + 1` times. In this version, `$times` specifies exactly the number of times the operation may run such that if
Expand Down
4 changes: 3 additions & 1 deletion src/retry.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ function retry($tries, callable $operation, callable $onError = null)
throw new FailingTooHardException($attempts, $exception);
}

$onError && $onError($exception);
if ($onError && $onError($exception) === false) {
return;
}

goto beginning;
}
Expand Down
19 changes: 18 additions & 1 deletion test/RetryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,23 @@ public function testErrorCallback()

self::assertInstanceOf(FailingTooHardException::class, $outerException);
self::assertSame($tries, $invocations);
self::assertSame(1, $errors);
self::assertSame($tries - 1, $errors);
}

public function testErrorCallbackHalt()
{
$invocations = 0;
try {
\ScriptFUSION\Retry\retry($tries = 2, function () use (&$invocations) {
++$invocations;

throw new \RuntimeException;
}, function () {
return false;
});
} catch (FailingTooHardException $exception) {
}

self::assertSame(1, $invocations);
}
}

0 comments on commit dfe63fb

Please sign in to comment.