Passed
Pull Request — master (#9)
by Shinji
10:53
created

RetryOnExceptionMiddleware::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of the sj-i/php-profiler package.
5
 *
6
 * (c) sji <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace PhpProfiler\Lib\Loop\LoopMiddleware;
15
16
use Exception;
17
use PhpProfiler\Lib\Loop\LoopMiddlewareInterface;
18
19
final class RetryOnExceptionMiddleware implements LoopMiddlewareInterface
20
{
21
    private LoopMiddlewareInterface $chain;
22
    /** @var array<int, class-string<Exception>> */
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<int, class-string<Exception>> at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array<int, class-string<Exception>>.
Loading history...
23
    private array $exception_names;
24
    private int $max_retry;
25
    private int $current_retry_count = 0;
26
27
    /**
28
     * RetryOnExceptionLoop constructor.
29
     * @param int $max_retry
30
     * @param array<int, class-string<Exception>> $exception_names
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<int, class-string<Exception>> at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array<int, class-string<Exception>>.
Loading history...
31
     * @param LoopMiddlewareInterface $chain
32
     */
33
    public function __construct(int $max_retry, array $exception_names, LoopMiddlewareInterface $chain)
34
    {
35
        $this->max_retry = $max_retry;
36
        $this->exception_names = $exception_names;
37
        $this->chain = $chain;
38
    }
39
40
    public function invoke(): bool
41
    {
42
        while ($this->current_retry_count <= $this->max_retry or $this->max_retry === -1) {
43
            try {
44
                $result = $this->chain->invoke();
45
                $this->current_retry_count = 0;
46
                return $result;
47
            } catch (Exception $e) {
48
                if (in_array(get_class($e), $this->exception_names, true)) {
49
                    $this->current_retry_count++;
50
                    continue;
51
                }
52
                throw $e;
53
            }
54
        }
55
        return false;
56
    }
57
}
58