OnExceptionRetryAction::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1
Metric Value
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4286
cc 1
eloc 5
nc 1
nop 4
crap 1
1
<?php
2
3
namespace Thruster\Component\Actions\Action;
4
5
use Thruster\Component\Actions\ExecutorInterface;
6
use Thruster\Component\Actions\ExecutorLessInterface;
7
8
/**
9
 * Class OnExceptionRetryAction
10
 *
11
 * @package Thruster\Component\Actions\Action
12
 * @author  Aurimas Niekis <[email protected]>
13
 */
14
class OnExceptionRetryAction extends BaseAction implements ExecutorLessInterface
15
{
16
    /**
17
     * @var array
18
     */
19
    protected $exceptions;
20
21
    /**
22
     * @var int
23
     */
24
    protected $retries;
25
26
    /**
27
     * @var callable
28
     */
29
    protected $beforeRetry;
30
31
    /**
32
     * @param               $action
33
     * @param array         $exceptions
34
     * @param int           $retries
35
     * @param callable $beforeRetry
36
     */
37 3
    public function __construct($action, array $exceptions, int $retries = 3, callable $beforeRetry = null)
38
    {
39 3
        $this->exceptions = $exceptions;
40 3
        $this->retries = $retries;
41 3
        $this->beforeRetry = $beforeRetry;
42
43 3
        parent::__construct($action);
44 3
    }
45
46 2
    public function parseArguments(ExecutorInterface $executor) : array
47
    {
48 2
        $result = [];
49
50 2
        for ($i = $this->retries; $i >= 0; $i--) {
51
            try {
52 2
                $result = parent::parseArguments($executor);
53 2
            } catch (\Throwable $thr) {
54 2
                if (in_array(get_class($thr), $this->exceptions)) {
55 2
                    if ($i > 0) {
56 2
                        call_user_func($this->beforeRetry, $thr);
57
58 2
                        continue;
59
                    }
60
                }
61
62 1
                throw new $thr;
63
            }
64
        }
65
66 1
        return $result;
67
    }
68
69
    /**
70
     * @inheritDoc
71
     */
72 1
    public function getName() : string
73
    {
74 1
        return 'thruster_on_exception_retry';
75
    }
76
77
}
78