Passed
Push — 0.6.x ( 8b7bff...29d9ce )
by Shinji
03:20 queued 01:42
created

RetryOnExceptionMiddleware::invoke()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 34
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 7
eloc 21
nc 5
nop 0
dl 0
loc 34
rs 8.6506
c 3
b 1
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 PhpProfiler\Lib\Log\Log;
17
use PhpProfiler\Lib\Loop\LoopMiddlewareInterface;
18
use Throwable;
19
20
final class RetryOnExceptionMiddleware implements LoopMiddlewareInterface
21
{
22
    private int $current_retry_count = 0;
23
24
    /**
25
     * @param array<int, class-string<Throwable>> $exception_names
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<int, class-string<Throwable>> at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array<int, class-string<Throwable>>.
Loading history...
26
     */
27
    public function __construct(
28
        private int $max_retry,
29
        private array $exception_names,
30
        private LoopMiddlewareInterface $chain,
31
    ) {
32
    }
33
34
    public function invoke(): bool
35
    {
36
        while ($this->current_retry_count <= $this->max_retry or $this->max_retry === -1) {
37
            try {
38
                $result = $this->chain->invoke();
39
                $this->current_retry_count = 0;
40
                return $result;
41
            } catch (Throwable $e) {
42
                foreach ($this->exception_names as $exception_name) {
43
                    /** @psalm-suppress DocblockTypeContradiction */
44
                    if (is_a($e, $exception_name)) {
45
                        $this->current_retry_count++;
46
                        Log::debug(
47
                            $e->getMessage(),
48
                            [
49
                                'retry_count' => $this->current_retry_count,
50
                                'trace' => $e->getTrace()
51
                            ]
52
                        );
53
                        continue 2;
54
                    }
55
                }
56
                throw $e;
57
            }
58
        }
59
        assert(isset($e) and $e instanceof Throwable);
60
        Log::error(
61
            $e->getMessage(),
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...
62
            [
63
                'retry_count' => $this->current_retry_count,
64
                'trace' => $e->getTrace()
65
            ]
66
        );
67
        throw $e;
68
    }
69
}
70