Completed
Push — master ( f6f5c2...e68441 )
by Vincenzo
02:13
created

CoverageCommand::run()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 19
rs 9.4285
cc 3
eloc 12
nc 3
nop 0
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
        $percentage = $this->getTargetCoverage();
21
        $inputFile = self::CLOVER_FILE;
22
        if (!file_exists($inputFile)) {
23
            throw new InvalidArgumentException(
24
                'Clover file not present, remember to run: phpunit --coverage-clover ' . $inputFile
25
            );
26
        }
27
        $coverage = $this->getCoverage($inputFile);
28
29
        if ($coverage < $percentage) {
30
            echo 'Code coverage is ' . $coverage . '%, which is below the accepted ' . $percentage . '%' . PHP_EOL;
31
            return 1;
32
        }
33
34
        echo 'Code coverage is ' . $coverage . '% - OK!' . PHP_EOL;
35
        return 0;
36
    }
37
38
    private function getCoverage($inputFile)
39
    {
40
        $xml = new SimpleXMLElement(file_get_contents($inputFile));
41
        $metrics = $xml->xpath('//metrics');
42
        $totalElements = 0;
43
        $checkedElements = 0;
44
45
        foreach ($metrics as $metric) {
46
            $totalElements += (int)$metric['elements'];
47
            $checkedElements += (int)$metric['coveredelements'];
48
        }
49
50
        return round(($checkedElements / $totalElements) * 100, 2);
51
    }
52
53
    private function getTargetCoverage()
54
    {
55
        $target = $this->getArg(0);
56
        $target = (int)(!empty($target) ? $target : 1);
57
        $percentage = min(100, max(0, $target));
58
        if (!$percentage) {
59
            throw new InvalidArgumentException('An integer checked percentage must be given as second parameter [0-100]');
60
        }
61
        return $percentage;
62
    }
63
}