RetryOnExceptionMiddleware   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 15
c 2
b 0
f 0
dl 0
loc 34
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A invoke() 0 20 6
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 int $current_retry_count = 0;
22
23
    /**
24
     * @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...
25
     */
26
    public function __construct(
27
        private int $max_retry,
28
        private array $exception_names,
29
        private LoopMiddlewareInterface $chain,
30
    ) {
31
    }
32
33
    public function invoke(): bool
34
    {
35
        while ($this->current_retry_count <= $this->max_retry or $this->max_retry === -1) {
36
            try {
37
                $result = $this->chain->invoke();
38
                $this->current_retry_count = 0;
39
                return $result;
40
            } catch (\Throwable $e) {
41
                foreach ($this->exception_names as $exception_name) {
42
                    /** @psalm-suppress DocblockTypeContradiction */
43
                    if (is_a($e, $exception_name)) {
44
                        $this->current_retry_count++;
45
                        continue 2;
46
                    }
47
                }
48
                throw $e;
49
            }
50
        }
51
        assert(isset($e));
52
        throw $e;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $e does not seem to be defined for all execution paths leading up to this point.
Loading history...
53
    }
54
}
55