Passed
Branch feature/first-release (57b0a8)
by Andrea Marco
13:40
created

RetriesHttpRequests::retry()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 23
rs 9.4222
cc 5
nc 3
nop 1
1
<?php
2
3
namespace Cerbero\LazyJsonPages\Concerns;
4
5
use Cerbero\LazyJsonPages\Exceptions\OutOfAttemptsException;
6
use Cerbero\LazyJsonPages\Outcome;
7
use Closure;
8
use Throwable;
9
10
/**
11
 * The trait to retry HTTP requests when they fail.
12
 *
13
 */
14
trait RetriesHttpRequests
15
{
16
    /**
17
     * Retry HTTP requests and keep track of their outcome
18
     *
19
     * @param callable $callback
20
     * @return mixed
21
     */
22
    protected function retry(callable $callback)
23
    {
24
        $attempt = 0;
25
        $outcome = new Outcome();
26
        $remainingAttempts = $this->config->attempts;
27
        $backoff = Closure::fromCallable($this->config->backoff ?: function (int $attempt) {
28
            return ($attempt - 1) ** 2 * 1000;
29
        });
30
31
        do {
32
            $attempt++;
33
            $remainingAttempts--;
34
35
            try {
36
                return $callback($outcome);
37
            } catch (Throwable $e) {
38
                if ($remainingAttempts > 0) {
39
                    usleep($backoff($attempt) * 1000);
40
                } else {
41
                    throw new OutOfAttemptsException($e, $outcome);
42
                }
43
            }
44
        } while ($remainingAttempts > 0);
45
    }
46
}
47