Completed
Push — master ( 9c21b6...43c791 )
by David
04:48
created

RetryPlugin::__construct()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 37

Duplication

Lines 16
Ratio 43.24 %

Code Coverage

Tests 16
CRAP Score 8.048

Importance

Changes 0
Metric Value
dl 16
loc 37
ccs 16
cts 26
cp 0.6153
rs 8.7057
c 0
b 0
f 0
cc 6
nc 7
nop 1
crap 8.048
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Http\Client\Common\Plugin;
6
7
use Http\Client\Common\Plugin;
8
use Http\Client\Exception;
9
use Http\Client\Exception\HttpException;
10
use Http\Promise\Promise;
11
use Psr\Http\Message\RequestInterface;
12
use Psr\Http\Message\ResponseInterface;
13
use Symfony\Component\OptionsResolver\OptionsResolver;
14
15
/**
16
 * Retry the request if an exception is thrown.
17
 *
18
 * By default will retry only one time.
19
 *
20
 * @author Joel Wurtz <[email protected]>
21
 */
22
final class RetryPlugin implements Plugin
23
{
24
    /**
25
     * Number of retry before sending an exception.
26
     *
27
     * @var int
28
     */
29
    private $retry;
30
31
    /**
32
     * @var callable
33
     */
34
    private $exceptionDelay;
35
36
    /**
37
     * @var callable
38
     */
39
    private $exceptionDecider;
40
41
    /**
42
     * Store the retry counter for each request.
43
     *
44
     * @var array
45
     */
46
    private $retryStorage = [];
47
48
    /**
49
     * @param array $config {
50
     *
51
     *     @var int $retries Number of retries to attempt if an exception occurs before letting the exception bubble up
52
     *     @var callable $exception_decider A callback that gets a request and an exception to decide after a failure whether the request should be retried
53
     *     @var callable $exception_delay A callback that gets a request, an exception and the number of retries and returns how many microseconds we should wait before trying again
54
     * }
55
     */
56 9
    public function __construct(array $config = [])
57
    {
58 9 View Code Duplication
        if (array_key_exists('decider', $config)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
59
            if (array_key_exists('exception_decider', $config)) {
60
                throw new \InvalidArgumentException('Do not set both the old "decider" and new "exception_decider" options');
61
            }
62
            trigger_error('The "decider" option has been deprecated in favour of "exception_decider"', E_USER_DEPRECATED);
63
            $config['exception_decider'] = $config['decider'];
64
            unset($config['decider']);
65
        }
66 9 View Code Duplication
        if (array_key_exists('delay', $config)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
67
            if (array_key_exists('exception_delay', $config)) {
68
                throw new \InvalidArgumentException('Do not set both the old "delay" and new "exception_delay" options');
69
            }
70
            trigger_error('The "delay" option has been deprecated in favour of "exception_delay"', E_USER_DEPRECATED);
71
            $config['exception_delay'] = $config['delay'];
72
            unset($config['delay']);
73
        }
74
75 9
        $resolver = new OptionsResolver();
76 9
        $resolver->setDefaults([
77 9
            'retries' => 1,
78
            'exception_decider' => function (RequestInterface $request, Exception $e) {
79
                // do not retry client errors
80 4
                return !$e instanceof HttpException || $e->getCode() >= 500;
81 9
            },
82
            'exception_delay' => __CLASS__.'::defaultDelay',
83
        ]);
84 9
        $resolver->setAllowedTypes('retries', 'int');
85 9
        $resolver->setAllowedTypes('exception_decider', 'callable');
86 9
        $resolver->setAllowedTypes('exception_delay', 'callable');
87 9
        $options = $resolver->resolve($config);
88
89 9
        $this->retry = $options['retries'];
90 9
        $this->exceptionDecider = $options['exception_decider'];
91 9
        $this->exceptionDelay = $options['exception_delay'];
92 9
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97 6
    public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
98
    {
99 6
        $chainIdentifier = spl_object_hash((object) $first);
100
101
        return $next($request)->then(function (ResponseInterface $response) use ($request, $chainIdentifier) {
102 3
            if (array_key_exists($chainIdentifier, $this->retryStorage)) {
103 2
                unset($this->retryStorage[$chainIdentifier]);
104
            }
105
106 3
            return $response;
107
        }, function (Exception $exception) use ($request, $next, $first, $chainIdentifier) {
108 5
            if (!array_key_exists($chainIdentifier, $this->retryStorage)) {
109 5
                $this->retryStorage[$chainIdentifier] = 0;
110
            }
111
112 5
            if ($this->retryStorage[$chainIdentifier] >= $this->retry) {
113 1
                unset($this->retryStorage[$chainIdentifier]);
114
115 1
                throw $exception;
116
            }
117
118 5
            if (!call_user_func($this->exceptionDecider, $request, $exception)) {
119 2
                throw $exception;
120
            }
121
122 3
            $time = call_user_func($this->exceptionDelay, $request, $exception, $this->retryStorage[$chainIdentifier]);
123 3
            usleep($time);
124
125
            // Retry synchronously
126 3
            ++$this->retryStorage[$chainIdentifier];
127 3
            $promise = $this->handleRequest($request, $next, $first);
128
129 3
            return $promise->wait();
130 6
        });
131
    }
132
133
    /**
134
     * @param int $retries The number of retries we made before. First time this get called it will be 0.
135
     *
136
     * @return int
137
     */
138 4
    public static function defaultDelay(RequestInterface $request, Exception $e, $retries)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $e is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
139
    {
140 4
        return pow(2, $retries) * 500000;
141
    }
142
}
143