Completed
Push — master ( 2f0aca...1e79f6 )
by Sebastian
03:02
created

CloverXML::getCoverage()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 2
nop 0
1
<?php
2
/**
3
 * This file is part of CaptainHook.
4
 *
5
 * (c) Sebastian Feldmann <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace sebastianfeldmann\CaptainHook\Hook\PHP\CoverageResolver;
11
12
use RuntimeException;
13
use sebastianfeldmann\CaptainHook\Hook\PHP\CoverageResolver;
14
use sebastianfeldmann\CaptainHook\Storage\File\Xml;
15
16
/**
17
 * Class CloverXML
18
 *
19
 * @package CaptainHook
20
 * @author  Sebastian Feldmann <[email protected]>
21
 * @link    https://github.com/sebastianfeldmann/captainhook
22
 * @since   Class available since Release 1.2.0
23
 */
24
class CloverXML implements CoverageResolver
25
{
26
    /**
27
     * Clover XML
28
     *
29
     * @var \SimpleXMLElement
30
     */
31
    private $xml;
32
33
    /**
34
     * CloverXML constructor.
35
     *
36
     * @param string $pathToCloverXml
37
     */
38
    public function __construct($pathToCloverXml)
39
    {
40
        $cloverFile = new Xml($pathToCloverXml);
41
        if (!$cloverFile->exists()) {
42
            throw new RuntimeException('could not find clover xml file: ' . $cloverFile->getPath());
43
        }
44
        $this->xml = $cloverFile->read();
45
        $this->validateXml();
46
    }
47
48
    /**
49
     * Make sure you have a valid xml structure
50
     *
51
     * @throws \RuntimeException
52
     */
53
    private function validateXml()
54
    {
55
        if (!isset($this->xml->project) || !isset($this->xml->project->metrics)) {
56
            throw new RuntimeException('invalid clover xml file');
57
        }
58
    }
59
60
    /**
61
     * Return test coverage in percent.
62
     *
63
     * @return float
64
     */
65
    public function getCoverage()
66
    {
67
        $statements = (string) $this->xml->project->metrics->attributes()->statements;
68
        $covered    = (string) $this->xml->project->metrics->attributes()->coveredstatements;
69
70
        if ($statements < 1 || !is_numeric($covered)) {
71
            throw new RuntimeException(
72
                'could not read coverage data from clover xml file ' .
73
                '(statements: ' . $statements . ', coveredstatements: ' . $covered . ')'
74
            );
75
        }
76
77
        return $covered / ($statements * 0.01);
78
    }
79
}
80