• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PHPCSStandards / PHP_CodeSniffer / 13848646538

14 Mar 2025 02:31AM UTC coverage: 78.685%. Remained the same
13848646538

Pull #878

github

web-flow
Merge 0a88cc579 into b07cf8269
Pull Request #878: MessageCollectorTest: data providers should be static

24837 of 31565 relevant lines covered (78.69%)

66.33 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/Reports/Code.php
1
<?php
2
/**
3
 * Full report for PHP_CodeSniffer.
4
 *
5
 * @author    Greg Sherwood <gsherwood@squiz.net>
6
 * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
7
 * @license   https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
8
 */
9

10
namespace PHP_CodeSniffer\Reports;
11

12
use Exception;
13
use PHP_CodeSniffer\Files\File;
14
use PHP_CodeSniffer\Util\Common;
15
use PHP_CodeSniffer\Util\Timing;
16

17
class Code implements Report
18
{
19

20

21
    /**
22
     * Generate a partial report for a single processed file.
23
     *
24
     * Function should return TRUE if it printed or stored data about the file
25
     * and FALSE if it ignored the file. Returning TRUE indicates that the file and
26
     * its data should be counted in the grand totals.
27
     *
28
     * @param array<string, string|int|array> $report      Prepared report data.
29
     *                                                     See the {@see Report} interface for a detailed specification.
30
     * @param \PHP_CodeSniffer\Files\File     $phpcsFile   The file being reported on.
31
     * @param bool                            $showSources Show sources?
32
     * @param int                             $width       Maximum allowed line width.
33
     *
34
     * @return bool
35
     */
36
    public function generateFileReport($report, File $phpcsFile, $showSources=false, $width=80)
×
37
    {
38
        if ($report['errors'] === 0 && $report['warnings'] === 0) {
×
39
            // Nothing to print.
40
            return false;
×
41
        }
42

43
        // How many lines to show above and below the error line.
44
        $surroundingLines = 2;
×
45

46
        $file   = $report['filename'];
×
47
        $tokens = $phpcsFile->getTokens();
×
48
        if (empty($tokens) === true) {
×
49
            if (PHP_CODESNIFFER_VERBOSITY === 1) {
×
50
                $startTime = microtime(true);
×
51
                echo 'CODE report is parsing '.basename($file).' ';
×
52
            } else if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
53
                echo "CODE report is forcing parse of $file".PHP_EOL;
×
54
            }
55

56
            try {
57
                $phpcsFile->parse();
×
58
            } catch (Exception $e) {
×
59
                // This is a second parse, so ignore exceptions.
60
                // They would have been added to the file's error list already.
61
            }
62

63
            if (PHP_CODESNIFFER_VERBOSITY === 1) {
×
64
                $timeTaken = ((microtime(true) - $startTime) * 1000);
×
65
                if ($timeTaken < 1000) {
×
66
                    $timeTaken = round($timeTaken);
×
67
                    echo "DONE in {$timeTaken}ms";
×
68
                } else {
69
                    $timeTaken = round(($timeTaken / 1000), 2);
×
70
                    echo "DONE in $timeTaken secs";
×
71
                }
72

73
                echo PHP_EOL;
×
74
            }
75

76
            $tokens = $phpcsFile->getTokens();
×
77
        }//end if
78

79
        // Create an array that maps lines to the first token on the line.
80
        $lineTokens = [];
×
81
        $lastLine   = 0;
×
82
        $stackPtr   = 0;
×
83
        foreach ($tokens as $stackPtr => $token) {
×
84
            if ($token['line'] !== $lastLine) {
×
85
                if ($lastLine > 0) {
×
86
                    $lineTokens[$lastLine]['end'] = ($stackPtr - 1);
×
87
                }
88

89
                $lastLine++;
×
90
                $lineTokens[$lastLine] = [
×
91
                    'start' => $stackPtr,
×
92
                    'end'   => null,
×
93
                ];
×
94
            }
95
        }
96

97
        // Make sure the last token in the file sits on an imaginary
98
        // last line so it is easier to generate code snippets at the
99
        // end of the file.
100
        $lineTokens[$lastLine]['end'] = $stackPtr;
×
101

102
        // Determine the longest code line we will be showing.
103
        $maxSnippetLength = 0;
×
104
        $eolLen           = strlen($phpcsFile->eolChar);
×
105
        foreach ($report['messages'] as $line => $lineErrors) {
×
106
            $startLine = max(($line - $surroundingLines), 1);
×
107
            $endLine   = min(($line + $surroundingLines), $lastLine);
×
108

109
            $maxLineNumLength = strlen($endLine);
×
110

111
            for ($i = $startLine; $i <= $endLine; $i++) {
×
112
                if ($i === 1) {
×
113
                    continue;
×
114
                }
115

116
                $lineLength       = ($tokens[($lineTokens[$i]['start'] - 1)]['column'] + $tokens[($lineTokens[$i]['start'] - 1)]['length'] - $eolLen);
×
117
                $maxSnippetLength = max($lineLength, $maxSnippetLength);
×
118
            }
119
        }
120

121
        $maxSnippetLength += ($maxLineNumLength + 8);
×
122

123
        // Determine the longest error message we will be showing.
124
        $maxErrorLength = 0;
×
125
        foreach ($report['messages'] as $lineErrors) {
×
126
            foreach ($lineErrors as $colErrors) {
×
127
                foreach ($colErrors as $error) {
×
128
                    $length = strlen($error['message']);
×
129
                    if ($showSources === true) {
×
130
                        $length += (strlen($error['source']) + 3);
×
131
                    }
132

133
                    $maxErrorLength = max($maxErrorLength, ($length + 1));
×
134
                }
135
            }
136
        }
137

138
        // The padding that all lines will require that are printing an error message overflow.
139
        if ($report['warnings'] > 0) {
×
140
            $typeLength = 7;
×
141
        } else {
142
            $typeLength = 5;
×
143
        }
144

145
        $errorPadding  = str_repeat(' ', ($maxLineNumLength + 7));
×
146
        $errorPadding .= str_repeat(' ', $typeLength);
×
147
        $errorPadding .= ' ';
×
148
        if ($report['fixable'] > 0) {
×
149
            $errorPadding .= '    ';
×
150
        }
151

152
        $errorPaddingLength = strlen($errorPadding);
×
153

154
        // The maximum amount of space an error message can use.
155
        $maxErrorSpace = ($width - $errorPaddingLength);
×
156
        if ($showSources === true) {
×
157
            // Account for the chars used to print colors.
158
            $maxErrorSpace += 8;
×
159
        }
160

161
        // Figure out the max report width we need and can use.
162
        $fileLength = strlen($file);
×
163
        $maxWidth   = max(($fileLength + 6), ($maxErrorLength + $errorPaddingLength));
×
164
        $width      = max(min($width, $maxWidth), $maxSnippetLength);
×
165
        if ($width < 70) {
×
166
            $width = 70;
×
167
        }
168

169
        // Print the file header.
170
        echo PHP_EOL."\033[1mFILE: ";
×
171
        if ($fileLength <= ($width - 6)) {
×
172
            echo $file;
×
173
        } else {
174
            echo '...'.substr($file, ($fileLength - ($width - 6)));
×
175
        }
176

177
        echo "\033[0m".PHP_EOL;
×
178
        echo str_repeat('-', $width).PHP_EOL;
×
179

180
        echo "\033[1m".'FOUND '.$report['errors'].' ERROR';
×
181
        if ($report['errors'] !== 1) {
×
182
            echo 'S';
×
183
        }
184

185
        if ($report['warnings'] > 0) {
×
186
            echo ' AND '.$report['warnings'].' WARNING';
×
187
            if ($report['warnings'] !== 1) {
×
188
                echo 'S';
×
189
            }
190
        }
191

192
        echo ' AFFECTING '.count($report['messages']).' LINE';
×
193
        if (count($report['messages']) !== 1) {
×
194
            echo 'S';
×
195
        }
196

197
        echo "\033[0m".PHP_EOL;
×
198

199
        foreach ($report['messages'] as $line => $lineErrors) {
×
200
            $startLine = max(($line - $surroundingLines), 1);
×
201
            $endLine   = min(($line + $surroundingLines), $lastLine);
×
202

203
            $snippet = '';
×
204
            if (isset($lineTokens[$startLine]) === true) {
×
205
                for ($i = $lineTokens[$startLine]['start']; $i <= $lineTokens[$endLine]['end']; $i++) {
×
206
                    $snippetLine = $tokens[$i]['line'];
×
207
                    if ($lineTokens[$snippetLine]['start'] === $i) {
×
208
                        // Starting a new line.
209
                        if ($snippetLine === $line) {
×
210
                            $snippet .= "\033[1m".'>> ';
×
211
                        } else {
212
                            $snippet .= '   ';
×
213
                        }
214

215
                        $snippet .= str_repeat(' ', ($maxLineNumLength - strlen($snippetLine)));
×
216
                        $snippet .= $snippetLine.':  ';
×
217
                        if ($snippetLine === $line) {
×
218
                            $snippet .= "\033[0m";
×
219
                        }
220
                    }
221

222
                    if (isset($tokens[$i]['orig_content']) === true) {
×
223
                        $tokenContent = $tokens[$i]['orig_content'];
×
224
                    } else {
225
                        $tokenContent = $tokens[$i]['content'];
×
226
                    }
227

228
                    if (strpos($tokenContent, "\t") !== false) {
×
229
                        $token            = $tokens[$i];
×
230
                        $token['content'] = $tokenContent;
×
231
                        if (stripos(PHP_OS, 'WIN') === 0) {
×
232
                            $tab = "\000";
×
233
                        } else {
234
                            $tab = "\033[30;1m»\033[0m";
×
235
                        }
236

237
                        $phpcsFile->tokenizer->replaceTabsInToken($token, $tab, "\000");
×
238
                        $tokenContent = $token['content'];
×
239
                    }
240

241
                    $tokenContent = Common::prepareForOutput($tokenContent, ["\r", "\n", "\t"]);
×
242
                    $tokenContent = str_replace("\000", ' ', $tokenContent);
×
243

244
                    $underline = false;
×
245
                    if ($snippetLine === $line && isset($lineErrors[$tokens[$i]['column']]) === true) {
×
246
                        $underline = true;
×
247
                    }
248

249
                    // Underline invisible characters as well.
250
                    if ($underline === true && trim($tokenContent) === '') {
×
251
                        $snippet .= "\033[4m".' '."\033[0m".$tokenContent;
×
252
                    } else {
253
                        if ($underline === true) {
×
254
                            $snippet .= "\033[4m";
×
255
                        }
256

257
                        $snippet .= $tokenContent;
×
258

259
                        if ($underline === true) {
×
260
                            $snippet .= "\033[0m";
×
261
                        }
262
                    }
263
                }//end for
264
            }//end if
265

266
            echo str_repeat('-', $width).PHP_EOL;
×
267

268
            foreach ($lineErrors as $colErrors) {
×
269
                foreach ($colErrors as $error) {
×
270
                    $padding = ($maxLineNumLength - strlen($line));
×
271
                    echo 'LINE '.str_repeat(' ', $padding).$line.': ';
×
272

273
                    if ($error['type'] === 'ERROR') {
×
274
                        echo "\033[31mERROR\033[0m";
×
275
                        if ($report['warnings'] > 0) {
×
276
                            echo '  ';
×
277
                        }
278
                    } else {
279
                        echo "\033[33mWARNING\033[0m";
×
280
                    }
281

282
                    echo ' ';
×
283
                    if ($report['fixable'] > 0) {
×
284
                        echo '[';
×
285
                        if ($error['fixable'] === true) {
×
286
                            echo 'x';
×
287
                        } else {
288
                            echo ' ';
×
289
                        }
290

291
                        echo '] ';
×
292
                    }
293

294
                    $message = $error['message'];
×
295
                    $message = str_replace("\n", "\n".$errorPadding, $message);
×
296
                    if ($showSources === true) {
×
297
                        $message = "\033[1m".$message."\033[0m".' ('.$error['source'].')';
×
298
                    }
299

300
                    $errorMsg = wordwrap(
×
301
                        $message,
×
302
                        $maxErrorSpace,
×
303
                        PHP_EOL.$errorPadding
×
304
                    );
×
305

306
                    echo $errorMsg.PHP_EOL;
×
307
                }//end foreach
308
            }//end foreach
309

310
            echo str_repeat('-', $width).PHP_EOL;
×
311
            echo rtrim($snippet).PHP_EOL;
×
312
        }//end foreach
313

314
        echo str_repeat('-', $width).PHP_EOL;
×
315
        if ($report['fixable'] > 0) {
×
316
            echo "\033[1m".'PHPCBF CAN FIX THE '.$report['fixable'].' MARKED SNIFF VIOLATIONS AUTOMATICALLY'."\033[0m".PHP_EOL;
×
317
            echo str_repeat('-', $width).PHP_EOL;
×
318
        }
319

320
        return true;
×
321

322
    }//end generateFileReport()
323

324

325
    /**
326
     * Prints all errors and warnings for each file processed.
327
     *
328
     * @param string $cachedData    Any partial report data that was returned from
329
     *                              generateFileReport during the run.
330
     * @param int    $totalFiles    Total number of files processed during the run.
331
     * @param int    $totalErrors   Total number of errors found during the run.
332
     * @param int    $totalWarnings Total number of warnings found during the run.
333
     * @param int    $totalFixable  Total number of problems that can be fixed.
334
     * @param bool   $showSources   Show sources?
335
     * @param int    $width         Maximum allowed line width.
336
     * @param bool   $interactive   Are we running in interactive mode?
337
     * @param bool   $toScreen      Is the report being printed to screen?
338
     *
339
     * @return void
340
     */
341
    public function generate(
×
342
        $cachedData,
343
        $totalFiles,
344
        $totalErrors,
345
        $totalWarnings,
346
        $totalFixable,
347
        $showSources=false,
348
        $width=80,
349
        $interactive=false,
350
        $toScreen=true
351
    ) {
352
        if ($cachedData === '') {
×
353
            return;
×
354
        }
355

356
        echo $cachedData;
×
357

358
        if ($toScreen === true && $interactive === false) {
×
359
            Timing::printRunTime();
×
360
        }
361

362
    }//end generate()
363

364

365
}//end class
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc