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

RetryParser   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 9
c 4
b 1
f 0
lcom 1
cbo 1
dl 0
loc 71
ccs 19
cts 19
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 1
A parsingFoundResult() 0 13 4
A isToBeRetried() 0 4 2
A hasNotExceededRetryCount() 0 4 1
A buildRegexPattern() 0 6 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