Completed
Push — master ( 7f5a29...8ce298 )
by Scott
13s
created

PhpCsLoader::getDescription()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
namespace exussum12\CoverageChecker;
3
4
use InvalidArgumentException;
5
use stdClass;
6
7
/**
8
 * Class PhpCsLoader
9
 * Used for reading json output from phpcs
10
 * @package exussum12\CoverageChecker
11
 */
12
class PhpCsLoader implements FileChecker
13
{
14
    /**
15
     * @var string
16
     */
17
    protected $json;
18
    /**
19
     * @var array
20
     */
21
    protected $invalidLines;
22
23
    /**
24
     * @var array
25
     */
26
27
    protected $failOnTypes = [
28
        'ERROR',
29
    ];
30
31
    /**
32
     * PhpCsLoader constructor.
33
     * @param string $filePath the file path to the json output from phpcs
34
     */
35
    public function __construct($filePath)
36
    {
37
        $this->json = json_decode(file_get_contents($filePath));
38
        if (json_last_error() !== JSON_ERROR_NONE) {
39
            throw new InvalidArgumentException(
40
                "Can't Parse phpcs json - " . json_last_error_msg()
41
            );
42
        }
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public function getLines()
49
    {
50
        $this->invalidLines = [];
51
        foreach ($this->json->files as $fileName => $file) {
52
            foreach ($file->messages as $message) {
53
                $this->addInvalidLine($fileName, $message);
54
            }
55
        }
56
57
        return $this->invalidLines;
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function isValidLine($file, $lineNumber)
64
    {
65
        return empty($this->invalidLines[$file][$lineNumber]);
66
    }
67
68
    /**
69
     * @param string $file
70
     * @param stdClass $message
71
     */
72
    protected function addInvalidLine($file, $message)
73
    {
74
        if (!in_array($message->type, $this->failOnTypes)) {
75
            return;
76
        }
77
        $line = $message->line;
78
79
        if (!isset($this->invalidLines[$file][$line])) {
80
            $this->invalidLines[$file][$line] = [];
81
        }
82
83
        $this->invalidLines[$file][$line][] = $message->message;
84
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89
    public function handleNotFoundFile()
90
    {
91
        return true;
92
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97
    public static function getDescription()
98
    {
99
        return 'Parses the json report format of phpcs, this mode ' .
100
            'only reports errors as violations';
101
    }
102
}
103