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

PHPCSStandards / PHP_CodeSniffer / 14516416464

17 Apr 2025 01:09PM UTC coverage: 77.945% (+0.3%) from 77.666%
14516416464

push

github

web-flow
Merge pull request #1010 from PHPCSStandards/phpcs-4.0/feature/sq-1612-stdout-vs-stderr

(Nearly) All status, debug, and progress output is now sent to STDERR instead of STDOUT

63 of 457 new or added lines in 18 files covered. (13.79%)

1 existing line in 1 file now uncovered.

19455 of 24960 relevant lines covered (77.94%)

78.64 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
use PHP_CodeSniffer\Util\Writers\StatusWriter;
17

18
class Code implements Report
19
{
20

21

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

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

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

57
            try {
58
                $phpcsFile->parse();
×
59

60
                // Make sure the fixer is aware of the reparsed file to prevent a race-condition
61
                // with the Diff report also re-parsing the file.
62
                $phpcsFile->fixer->startFile($phpcsFile);
×
63
            } catch (Exception $e) {
×
64
                // This is a second parse, so ignore exceptions.
65
                // They would have been added to the file's error list already.
66
            }
67

68
            if (PHP_CODESNIFFER_VERBOSITY === 1) {
×
69
                $timeTaken = ((microtime(true) - $startTime) * 1000);
×
70
                if ($timeTaken < 1000) {
×
71
                    $timeTaken = round($timeTaken);
×
NEW
72
                    StatusWriter::forceWrite("DONE in {$timeTaken}ms");
×
73
                } else {
74
                    $timeTaken = round(($timeTaken / 1000), 2);
×
NEW
75
                    StatusWriter::forceWrite("DONE in $timeTaken secs");
×
76
                }
77
            }
78

79
            $tokens = $phpcsFile->getTokens();
×
80
        }//end if
81

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

92
                $lastLine++;
×
93
                $lineTokens[$lastLine] = [
×
94
                    'start' => $stackPtr,
×
95
                    'end'   => null,
×
96
                ];
×
97
            }
98
        }
99

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

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

112
            $maxLineNumLength = strlen($endLine);
×
113

114
            for ($i = $startLine; $i <= $endLine; $i++) {
×
115
                if ($i === 1) {
×
116
                    continue;
×
117
                }
118

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

124
        $maxSnippetLength += ($maxLineNumLength + 8);
×
125

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

136
                    $maxErrorLength = max($maxErrorLength, ($length + 1));
×
137
                }
138
            }
139
        }
140

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

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

155
        $errorPaddingLength = strlen($errorPadding);
×
156

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

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

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

180
        echo "\033[0m".PHP_EOL;
×
181
        echo str_repeat('-', $width).PHP_EOL;
×
182

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

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

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

200
        echo "\033[0m".PHP_EOL;
×
201

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

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

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

225
                    if (isset($tokens[$i]['orig_content']) === true) {
×
226
                        $tokenContent = $tokens[$i]['orig_content'];
×
227
                    } else {
228
                        $tokenContent = $tokens[$i]['content'];
×
229
                    }
230

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

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

244
                    $tokenContent = Common::prepareForOutput($tokenContent, ["\r", "\n", "\t"]);
×
245
                    $tokenContent = str_replace("\000", ' ', $tokenContent);
×
246

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

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

260
                        $snippet .= $tokenContent;
×
261

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

269
            echo str_repeat('-', $width).PHP_EOL;
×
270

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

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

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

294
                        echo '] ';
×
295
                    }
296

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

303
                    $errorMsg = wordwrap(
×
304
                        $message,
×
305
                        $maxErrorSpace,
×
306
                        PHP_EOL.$errorPadding
×
307
                    );
×
308

309
                    echo $errorMsg.PHP_EOL;
×
310
                }//end foreach
311
            }//end foreach
312

313
            echo str_repeat('-', $width).PHP_EOL;
×
314
            echo rtrim($snippet).PHP_EOL;
×
315
        }//end foreach
316

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

323
        return true;
×
324

325
    }//end generateFileReport()
326

327

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

359
        echo $cachedData;
×
360

361
        if ($toScreen === true && $interactive === false) {
×
362
            Timing::printRunTime();
×
363
        }
364

365
    }//end generate()
366

367

368
}//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