Passed
Push — master ( 902a34...c826a7 )
by Kyle
53s queued 11s
created

SARIFRenderer::pathToArtifactLocation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of PHP Mess Detector.
4
 *
5
 * Copyright (c) Manuel Pichler <[email protected]>.
6
 * All rights reserved.
7
 *
8
 * Licensed under BSD License
9
 * For full copyright and license information, please see the LICENSE file.
10
 * Redistributions of files must retain the above copyright notice.
11
 *
12
 * @author Lukas Bestle <[email protected]>
13
 * @copyright Manuel Pichler. All rights reserved.
14
 * @license https://opensource.org/licenses/bsd-license.php BSD License
15
 * @link http://phpmd.org/
16
 */
17
18
namespace PHPMD\Renderer;
19
20
use PHPMD\PHPMD;
21
use PHPMD\Report;
22
use PHPMD\Renderer\JSONRenderer;
23
24
/**
25
 * This class will render a SARIF (Static Analysis
26
 * Results Interchange Format) report.
27
 */
28
class SARIFRenderer extends JSONRenderer
29
{
30
    /**
31
     * Create report data and add renderer meta properties
32
     *
33
     * @return array
34
     */
35
    protected function initReportData()
36
    {
37
        $data = array(
38
            'version' => '2.1.0',
39
            '$schema' =>
40
                'https://raw.githubusercontent.com/oasis-tcs/' .
41
                'sarif-spec/master/Schemata/sarif-schema-2.1.0.json',
42
            'runs' => array(
43
                array(
44
                    'tool' => array(
45
                        'driver' => array(
46
                            'name' => 'PHPMD',
47
                            'informationUri' => 'https://phpmd.org',
48
                            'version' => PHPMD::VERSION,
49
                            'rules' => array(),
50
                        ),
51
                    ),
52
                    'originalUriBaseIds' => array(
53
                        'WORKINGDIR' => array(
54
                            'uri' => static::pathToUri(getcwd()) . '/',
55
                        ),
56
                    ),
57
                    'results' => array(),
58
                ),
59
            ),
60
        );
61
62
        return $data;
0 ignored issues
show
Best Practice introduced by
The expression return $data; seems to be an array, but some of its elements' types (array<string,array>[]) are incompatible with the return type of the parent method PHPMD\Renderer\JSONRenderer::initReportData of type array<string,string>.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
63
    }
64
65
    /**
66
     * Add violations, if any, to the report data
67
     *
68
     * @param Report $report The report with potential violations.
69
     * @param array $data The report output to add the violations to.
70
     * @return array The report output with violations, if any.
71
     */
72
    protected function addViolationsToReport(Report $report, array $data)
73
    {
74
        $rules = array();
75
        $results = array();
76
        $ruleIndices = array();
77
78
        /** @var RuleViolation $violation */
79
        foreach ($report->getRuleViolations() as $violation) {
80
            $rule = $violation->getRule();
81
            $ruleRef = str_replace(' ', '', $rule->getRuleSetName()) . '/' . $rule->getName();
82
83
            if (!isset($ruleIndices[$ruleRef])) {
84
                $ruleIndices[$ruleRef] = count($rules);
85
86
                $ruleData = array(
87
                    'id' => $ruleRef,
88
                    'name' => $rule->getName(),
89
                    'shortDescription' => array(
90
                        'text' => $rule->getRuleSetName() . ': ' . $rule->getName(),
91
                    ),
92
                    'messageStrings' => array(
93
                        'default' => array(
94
                            'text' => trim($rule->getMessage()),
95
                        ),
96
                    ),
97
                    'help' => array(
98
                        'text' => trim(str_replace("\n", ' ', $rule->getDescription())),
99
                    ),
100
                    'helpUri' => $rule->getExternalInfoUrl(),
101
                    'properties' => array(
102
                        'ruleSet' => $rule->getRuleSetName(),
103
                        'priority' => $rule->getPriority(),
104
                    ),
105
                );
106
107
                $examples = $rule->getExamples();
108
                if (!empty($examples)) {
109
                    $ruleData['help']['markdown'] =
110
                        $ruleData['help']['text'] .
111
                        "\n\n### Example\n\n```php\n" .
112
                        implode("\n```\n\n```php\n", array_map('trim', $examples)) . "\n```";
113
                }
114
115
                $since = $rule->getSince();
116
                if ($since) {
117
                    $ruleData['properties']['since'] = 'PHPMD ' . $since;
118
                }
119
120
                $rules[] = $ruleData;
121
            }
122
123
            $arguments = $violation->getArgs();
124
            if ($arguments === null) {
125
                $arguments = array();
126
            }
127
128
            $results[] = array(
129
                'ruleId' => $ruleRef,
130
                'ruleIndex' => $ruleIndices[$ruleRef],
131
                'message' => array(
132
                    'id' => 'default',
133
                    'arguments' => array_map('strval', $arguments),
134
                    'text' => $violation->getDescription(),
135
                ),
136
                'locations' => array(
137
                    array(
138
                        'physicalLocation' => array(
139
                            'artifactLocation' => static::pathToArtifactLocation($violation->getFileName()),
140
                            'region' => array(
141
                                'startLine' => $violation->getBeginLine(),
142
                                'endLine' => $violation->getEndLine(),
143
                            ),
144
                        ),
145
                    )
146
                ),
147
            );
148
        }
149
150
        $data['runs'][0]['tool']['driver']['rules'] = $rules;
151
        $data['runs'][0]['results'] = array_merge($data['runs'][0]['results'], $results);
152
153
        return $data;
154
    }
155
156
    /**
157
     * Add errors, if any, to the report data
158
     *
159
     * @param Report $report The report with potential errors.
160
     * @param array $data The report output to add the errors to.
161
     * @return array The report output with errors, if any.
162
     */
163
    protected function addErrorsToReport(Report $report, array $data)
164
    {
165
        $errors = $report->getErrors();
166
        if ($errors) {
167
            foreach ($errors as $error) {
168
                $data['runs'][0]['results'][] = array(
169
                    'level' => 'error',
170
                    'message' => array(
171
                        'text' => $error->getMessage(),
172
                    ),
173
                    'locations' => array(
174
                        array(
175
                            'physicalLocation' => array(
176
                                'artifactLocation' => static::pathToArtifactLocation($error->getFile()),
177
                            ),
178
                        )
179
                    ),
180
                );
181
            }
182
        }
183
184
        return $data;
185
    }
186
187
    /**
188
     * Makes an absolute path relative to the working directory
189
     * if possible, otherwise prepends the `file://` protocol
190
     * and returns the result as a SARIF `artifactLocation`
191
     *
192
     * @param string $path
193
     * @return array
194
     */
195
    protected static function pathToArtifactLocation($path)
196
    {
197
        $workingDir = getcwd();
198
        if (substr($path, 0, strlen($workingDir)) === $workingDir) {
199
            // relative path
200
            return array(
201
                'uri' => substr($path, strlen($workingDir) + 1),
202
                'uriBaseId' => 'WORKINGDIR',
203
            );
204
        }
205
        
206
        // absolute path with protocol
207
        return array(
208
            'uri' => static::pathToUri($path),
209
        );
210
    }
211
212
    /**
213
     * Converts an absolute path to a file:// URI
214
     *
215
     * @param string $path
216
     * @return string
217
     */
218
    protected static function pathToUri($path)
219
    {
220
        $path = str_replace(DIRECTORY_SEPARATOR, '/', $path);
221
222
        // file:///C:/... on Windows systems
223
        if (substr($path, 0, 1) !== '/') {
224
            $path = '/' . $path;
225
        }
226
227
        return 'file://' . $path;
228
    }
229
}
230