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

PHPCSStandards / PHP_CodeSniffer / 14732428675

29 Apr 2025 01:26PM UTC coverage: 78.394% (+0.1%) from 78.295%
14732428675

Pull #1052

github

web-flow
Merge 1df4347f5 into d12e243d8
Pull Request #1052: Fixer: remove output buffering

19546 of 24933 relevant lines covered (78.39%)

86.19 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\Writers\StatusWriter;
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
                StatusWriter::forceWrite('CODE report is parsing '.basename($file).' ', 0, 0);
×
52
            } else if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
53
                StatusWriter::forceWrite("CODE report is forcing parse of $file");
×
54
            }
55

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

259
                        $snippet .= $tokenContent;
×
260

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

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

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

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

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

293
                        echo '] ';
×
294
                    }
295

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

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

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

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

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

322
        return true;
×
323

324
    }//end generateFileReport()
325

326

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

358
        echo $cachedData;
×
359

360
    }//end generate()
361

362

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

© 2026 Coveralls, Inc