Completed
Push — master ( aa9657...bb9832 )
by Sebastian
05:21
created

CloverXML::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
c 0
b 0
f 0
ccs 7
cts 7
cp 1
rs 9.6666
cc 2
eloc 6
nc 2
nop 1
crap 2
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 6
    public function __construct($pathToCloverXml)
39
    {
40 6
        $cloverFile = new Xml($pathToCloverXml);
41 6
        if (!$cloverFile->exists()) {
42 1
            throw new RuntimeException('could not find clover xml file: ' . $cloverFile->getPath());
43
        }
44 5
        $this->xml = $cloverFile->read();
45 5
        $this->validateXml();
46 4
    }
47
48
    /**
49
     * Make sure you have a valid xml structure
50
     *
51
     * @throws \RuntimeException
52
     */
53 5
    private function validateXml()
54
    {
55 5
        if (!isset($this->xml->project) || !isset($this->xml->project->metrics)) {
56 1
            throw new RuntimeException('invalid clover xml file');
57
        }
58 4
    }
59
60
    /**
61
     * Return test coverage in percent.
62
     *
63
     * @return float
64
     */
65 4
    public function getCoverage() : float
66
    {
67 4
        $statements = (string) $this->xml->project->metrics->attributes()->statements;
68 4
        $covered    = (string) $this->xml->project->metrics->attributes()->coveredstatements;
69
70 4
        if ($statements < 1 || !is_numeric($covered)) {
71 1
            throw new RuntimeException(
72
                'could not read coverage data from clover xml file ' .
73 1
                '(statements: ' . $statements . ', coveredstatements: ' . $covered . ')'
74
            );
75
        }
76
77 3
        return $covered / ($statements * 0.01);
78
    }
79
}
80