Completed
Push — master ( 1a3a48...6e0e69 )
by Alessandro
09:39 queued 07:07
created

RetryParser::processWillBeRetried()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

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