BinaryExponentialBackoff::handleRetry()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 2
1
<?php
2
namespace Workana\AsyncJobs\Retry;
3
4
use InvalidArgumentException;
5
use Bernard\Envelope;
6
use Workana\AsyncJobs\Job;
7
8
/**
9
 * Binary Exponential Backoff is an algorithm that uses feedback to multiplicatively
10
 * decrease the rate of some process, in order to gradually find an acceptable rate.
11
 *
12
 * @author Carlos Frutos <[email protected]>
13
 */
14
class BinaryExponentialBackoff extends RetryStrategy
15
{
16
    /**
17
     * {@inheritDoc}
18
     */
19
    public function handleRetry(Envelope $envelope, $error)
20
    {
21
        $job = $envelope->getMessage();
22
23
        if (!($job instanceof Job)) {
24
            throw new InvalidArgumentException('Envelope message must have a valid job instance');
25
        }
26
27
        if (!$job->areRetriesExhausted()) {
28
            $job->incrementRetries();
29
            $this->redispatch($job);
30
        }
31
    }
32
33
    /**
34
     * Redispatch job
35
     *
36
     * @param Job $job
37
     *
38
     * @return void
39
     */
40
    private function redispatch(Job $job)
41
    {
42
        $delay = pow(2, $job->getRetries());
43
44
        $job->withDelay($delay);
45
46
        $this->jm->dispatch($job);
47
    }
48
}