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

CoverageCommand   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
c 1
b 0
f 0
lcom 0
cbo 1
dl 0
loc 51
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B run() 0 28 5
A getCoverage() 0 14 2
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
}