Completed
Push — master ( 690e08...eac5eb )
by Vincenzo
02:15
created

CoverageCommand::getCoverage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 14
rs 9.4285
cc 2
eloc 9
nc 2
nop 1
1
<?php
2
3
4
namespace App\Console;
5
6
7
use App\Lib\Slime\Console\SlimeCommand;
8
use InvalidArgumentException;
9
use SimpleXMLElement;
10
11
class CoverageCommand extends SlimeCommand
12
{
13
    const CLOVER_FILE = 'clover.xml';
14
15
    /**
16
     * @return int
17
     */
18
    public function run()
19
    {
20
        $targetCoverage = $this->getArg(0);
21
22
        $inputFile = self::CLOVER_FILE;
23
        $targetCoverage = (int)(!empty($targetCoverage) ? $targetCoverage : 1);
24
        $percentage = min(100, max(0, $targetCoverage));
25
26
        if (!file_exists($inputFile)) {
27
            throw new InvalidArgumentException(
28
                'Clover file not present, remember to run: phpunit --coverage-clover ' . $inputFile
29
            );
30
        }
31
32
        if (!$percentage) {
33
            throw new InvalidArgumentException('An integer checked percentage must be given as second parameter');
34
        }
35
        $coverage = $this->getCoverage($inputFile);
36
37
38
        if ($coverage < $percentage) {
39
            echo 'Code coverage is ' . $coverage . '%, which is below the accepted ' . $percentage . '%' . PHP_EOL;
40
            return 1;
41
        }
42
43
        echo 'Code coverage is ' . $coverage . '% - OK!' . PHP_EOL;
44
        return 0;
45
    }
46
47
    private function getCoverage($inputFile)
48
    {
49
        $xml = new SimpleXMLElement(file_get_contents($inputFile));
50
        $metrics = $xml->xpath('//metrics');
51
        $totalElements = 0;
52
        $checkedElements = 0;
53
54
        foreach ($metrics as $metric) {
55
            $totalElements += (int)$metric['elements'];
56
            $checkedElements += (int)$metric['coveredelements'];
57
        }
58
59
        return round(($checkedElements / $totalElements) * 100, 2);
60
    }
61
}