Completed
Push — master ( 08d1d7...894d82 )
by Shinji
16s queued 11s
created

RetryOnExceptionMiddlewareAsync   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 17
dl 0
loc 34
c 1
b 0
f 1
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A invoke() 0 13 5
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\AsyncLoopMiddleware;
15
16
use Exception;
17
use PhpProfiler\Lib\Loop\AsyncLoopMiddlewareInterface;
18
19
final class RetryOnExceptionMiddlewareAsync implements AsyncLoopMiddlewareInterface
20
{
21
    private AsyncLoopMiddlewareInterface $chain;
22
    /** @var array<int, class-string<Exception>> */
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
31
     * @param AsyncLoopMiddlewareInterface $chain
32
     */
33
    public function __construct(int $max_retry, array $exception_names, AsyncLoopMiddlewareInterface $chain)
34
    {
35
        $this->max_retry = $max_retry;
36
        $this->exception_names = $exception_names;
37
        $this->chain = $chain;
38
    }
39
40
    public function invoke(): \Generator
41
    {
42
        while ($this->current_retry_count <= $this->max_retry or $this->max_retry === -1) {
43
            try {
44
                yield from $this->chain->invoke();
45
            } catch (Exception $e) {
46
                if (in_array(get_class($e), $this->exception_names, true)) {
47
                    $this->current_retry_count++;
48
                    continue;
49
                }
50
                throw $e;
51
            }
52
            $this->current_retry_count = 0;
53
        }
54
    }
55
}
56