Passed
Push — master ( 8df2bc...bb46b9 )
by Scott
36s
created

PhpunitFilter   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 71
rs 10
c 0
b 0
f 0
wmc 14
lcom 1
cbo 2

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
C getTestsForRunning() 0 28 7
A endsWith() 0 5 1
A stripFileExtension() 0 5 1
A groupTestsBySuite() 0 14 3
1
<?php
2
namespace exussum12\coverageChecker;
3
4
use Exception;
5
6
class PhpunitFilter
7
{
8
    protected $diff;
9
    protected $matcher;
10
    protected $coverage;
11
    public function __construct(DiffFileLoader $diff, FileMatcher $matcher, $coveragePhp)
12
    {
13
        if (!is_readable(($coveragePhp))) {
14
            throw new Exception("Coverage File not found");
15
        }
16
        $this->coverage = include($coveragePhp);
17
        $this->diff = $diff;
18
        $this->matcher = $matcher;
19
    }
20
21
    public function getTestsForRunning()
22
    {
23
        $changes = $this->diff->getChangedLines();
24
        $testData = $this->coverage->getData();
25
        $fileNames = array_keys($testData);
26
        $runTests = [];
27
        foreach ($changes as $file => $lines) {
28
            try {
29
                if ($found = $this->matcher->match($file, $fileNames)) {
30
                    foreach ($lines as $line) {
31
                        if (isset($testData[$found][$line])) {
32
                            $runTests = array_unique(
33
                                array_merge(
34
                                    $runTests,
35
                                    $testData[$found][$line]
36
                                )
37
                            );
38
                        }
39
                    }
40
                }
41
            } catch (Exception $e) {
42
                if ($this->endsWith($file, ".php")) {
43
                    $runTests[] = $this->stripFileExtension($file);
44
                }
45
            }
46
        }
47
        return $this->groupTestsBySuite($runTests);
48
    }
49
50
    protected function endsWith($haystack, $needle)
51
    {
52
        $length = strlen($needle);
53
        return (substr($haystack, -$length) === $needle);
54
    }
55
56
    protected function stripFileExtension($file)
57
    {
58
        $ext = ".php";
59
        return str_replace('/', '\\', substr($file, 0, -strlen($ext)));
60
    }
61
62
    protected function groupTestsBySuite($tests)
63
    {
64
        $groupedTests = [];
65
        foreach ($tests as $test) {
66
            $suite = $test;
67
            $testName = '';
68
69
            if (strpos($test, '::') > 0) {
70
                list ($suite, $testName) = explode('::', $test);
71
            }
72
            $groupedTests[$suite][] = $testName;
73
        }
74
        return $groupedTests;
75
    }
76
}
77