Completed
Push — master ( 4d754f...61a7b9 )
by Aurimas
06:56
created

OnExceptionRetryAction::parseArguments()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5.025
Metric Value
dl 0
loc 18
ccs 9
cts 10
cp 0.9
rs 8.8571
cc 5
eloc 10
nc 5
nop 1
crap 5.025
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 1
    public function __construct($action, array $exceptions, int $retries = 3, callable $beforeRetry = null)
38
    {
39 1
        $this->exceptions = $exceptions;
40 1
        $this->retries = $retries;
41 1
        $this->beforeRetry = $beforeRetry;
42
43 1
        parent::__construct($action);
44 1
    }
45
46 1
    public function parseArguments(ExecutorInterface $executor) : array
47
    {
48 1
        for ($i = $this->retries; $i >= 0; $i--) {
49
            try {
50 1
                return parent::parseArguments($executor);
51 1
            } catch (\Throwable $thr) {
52 1
                if (in_array(get_class($thr), $this->exceptions)) {
53 1
                    if ($i > 0) {
54 1
                        call_user_func($this->beforeRetry, $thr);
55
56 1
                        continue;
57
                    }
58
                }
59
60 1
                throw new $thr;
61
            }
62
        }
63
    }
64
65
    /**
66
     * @inheritDoc
67
     */
68
    public function getName() : string
69
    {
70
        return 'thruster_on_exception_retry';
71
    }
72
73
}
74