Completed
Push — output_parsers_refactor ( 9ffc6c...755930 )
by Alessandro
09:57
created

RetryParser::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
ccs 9
cts 9
cp 1
rs 9.4285
cc 1
eloc 8
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Paraunit\Parser;
4
5
use Paraunit\Process\ProcessResultInterface;
6
use Paraunit\Process\RetryAwareInterface;
7
8
/**
9
 * Class RetryParser
10
 * @package Paraunit\Parser
11
 */
12
class RetryParser implements JSONParserChainElementInterface
13
{
14
    /** @var  int */
15
    private $maxRetryCount;
16
17
    /** @var  string */
18
    private $regexPattern;
19
20
    /**
21
     * RetryParser constructor.
22
     * @param int $maxRetryCount
23
     */
24 20
    public function __construct($maxRetryCount = 3)
25
    {
26 20
        $this->maxRetryCount = $maxRetryCount;
27
28
        $patterns = array(
29 20
            'The EntityManager is closed',
30
            // MySQL
31 20
            'Deadlock found',
32 20
            'Lock wait timeout exceeded',
33
            // SQLite
34 20
            'General error: 5 database is locked',
35 20
        );
36
37 20
        $this->regexPattern = $this->buildRegexPattern($patterns);
38 20
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function parsingFoundResult(ProcessResultInterface $process, \stdClass $log)
44
    {
45 20
        if ($process instanceof RetryAwareInterface
46
            && $this->isToBeRetried($log)
47 20
            && $this->hasNotExceededRetryCount($process)
48 7
        ) {
49
            $process->markAsToBeRetried();
50 7
51
            return true;
52
        }
53 16
54
        return false;
55
    }
56
57
    /**
58
     * @param \stdClass $log
59
     * @return bool
60 20
     */
61
    private function isToBeRetried(\stdClass $log)
62 20
    {
63
        return $log->status == 'error' && preg_match($this->regexPattern, $log->message);
64
    }
65
66
67
    private function hasNotExceededRetryCount(RetryAwareInterface $process)
68
    {
69 20
        return $process->getRetryCount() < $this->maxRetryCount;
70
    }
71 20
72
    /**
73 20
     * @param array | string[] $patterns
74
     * @return string
75
     */
76
    private function buildRegexPattern(array $patterns)
77
    {
78
        $regex = implode('|', $patterns);
79
80
        return '/' . $regex . '/';
81
    }
82
}
83