Completed
Push — master ( 9272ce...7209dc )
by Alessandro
11:18 queued 04:28
created

CoverageFetcher::overrideCoverageClassDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 13
ccs 0
cts 0
cp 0
rs 9.4285
cc 1
eloc 8
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Paraunit\Coverage;
4
5
use Paraunit\Configuration\TempFilenameFactory;
6
use Paraunit\Process\AbstractParaunitProcess;
7
use Paraunit\Proxy\Coverage\CodeCoverage;
8
use Symfony\Component\Process\Process;
9
10
/**
11
 * Class CoverageFetcher
12
 * @package Paraunit\Coverage
13
 */
14
class CoverageFetcher
15
{
16
    /** @var  TempFilenameFactory */
17
    private $tempFilenameFactory;
18
19
    /**
20
     * CoverageFetcher constructor.
21
     * @param TempFilenameFactory $tempFilenameFactory
22
     */
23 3
    public function __construct(TempFilenameFactory $tempFilenameFactory)
24
    {
25 3
        $this->tempFilenameFactory = $tempFilenameFactory;
26 3
    }
27
28
    /**
29
     * @param AbstractParaunitProcess $process
30
     * @return CodeCoverage
31
     */
32 3
    public function fetch(AbstractParaunitProcess $process)
33
    {
34 3
        $tempFilename = $this->tempFilenameFactory->getFilenameForCoverage($process->getUniqueId());
35 3
        $codeCoverage = null;
36
37 3
        if ($this->coverageFileIsValid($tempFilename)) {
38 2
            $codeCoverage = require $tempFilename;
39 2
            unlink($tempFilename);
40 2
        }
41
42 3
        if ($codeCoverage instanceof CodeCoverage) {
43 1
            return $codeCoverage;
44
        }
45
46 2
        return new CodeCoverage();
47
    }
48
49
    /**
50
     * @param string $tempFilename
51
     * @return bool
52
     */
53 3
    private function coverageFileIsValid($tempFilename)
54
    {
55 3
        if (! file_exists($tempFilename)) {
56 1
            return false;
57
        }
58
59
        try {
60 2
            $this->overrideCoverageClassDefinition($tempFilename);
61 2
62 2
            $verificationProcess = new Process('php --syntax-check ' . $tempFilename);
63
            $verificationProcess->start();
64 2
            $verificationProcess->wait();
65
66
            return $verificationProcess->getExitCode() === 0;
67
        } catch (\Exception $e) {
68
            return false;
69
        }
70
    }
71
72
    /**
73
     * @param string $tempFilename
74
     */
75
    private function overrideCoverageClassDefinition($tempFilename)
76
    {
77
        $fileContent = str_replace(
78
            array(
79
                'new SebastianBergmann\CodeCoverage\CodeCoverage',
80
                'new PHP_CodeCoverage'
81
            ),
82
            'new Paraunit\Proxy\Coverage\CodeCoverage',
83
            file_get_contents($tempFilename)
84
        );
85
86
        file_put_contents($tempFilename, $fileContent);
87
    }
88
}
89