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

PHPCSStandards / PHP_CodeSniffer / 17662127818

12 Sep 2025 01:50AM UTC coverage: 78.786%. Remained the same
17662127818

push

github

web-flow
Merge pull request #1241 from PHPCSStandards/phpcs-4.x/feature/155-normalize-some-code-style-rules-3

CS: normalize code style rules [3]

343 of 705 new or added lines in 108 files covered. (48.65%)

3 existing lines in 3 files now uncovered.

19732 of 25045 relevant lines covered (78.79%)

96.47 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(array $report, File $phpcsFile, bool $showSources = false, int $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) {
×
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) {
×
NEW
69
                StatusWriter::forceWrite('DONE in ' . Timing::getHumanReadableDuration(Timing::getDurationSince($startTime)));
×
70
            }
71

72
            $tokens = $phpcsFile->getTokens();
×
73
        }//end if
74

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

85
                $lastLine++;
×
86
                $lineTokens[$lastLine] = [
×
87
                    'start' => $stackPtr,
×
88
                    'end'   => null,
×
89
                ];
×
90
            }
91
        }
92

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

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

105
            $maxLineNumLength = strlen($endLine);
×
106

107
            for ($i = $startLine; $i <= $endLine; $i++) {
×
108
                if ($i === 1) {
×
109
                    continue;
×
110
                }
111

112
                $lineLength       = ($tokens[($lineTokens[$i]['start'] - 1)]['column'] + $tokens[($lineTokens[$i]['start'] - 1)]['length'] - $eolLen);
×
113
                $maxSnippetLength = max($lineLength, $maxSnippetLength);
×
114
            }
115
        }
116

117
        $maxSnippetLength += ($maxLineNumLength + 8);
×
118

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

129
                    $maxErrorLength = max($maxErrorLength, ($length + 1));
×
130
                }
131
            }
132
        }
133

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

141
        $errorPadding  = str_repeat(' ', ($maxLineNumLength + 7));
×
142
        $errorPadding .= str_repeat(' ', $typeLength);
×
143
        $errorPadding .= ' ';
×
144
        if ($report['fixable'] > 0) {
×
145
            $errorPadding .= '    ';
×
146
        }
147

148
        $errorPaddingLength = strlen($errorPadding);
×
149

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

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

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

NEW
173
        echo "\033[0m" . PHP_EOL;
×
NEW
174
        echo str_repeat('-', $width) . PHP_EOL;
×
175

NEW
176
        echo "\033[1m" . 'FOUND ' . $report['errors'] . ' ERROR';
×
177
        if ($report['errors'] !== 1) {
×
178
            echo 'S';
×
179
        }
180

181
        if ($report['warnings'] > 0) {
×
NEW
182
            echo ' AND ' . $report['warnings'] . ' WARNING';
×
183
            if ($report['warnings'] !== 1) {
×
184
                echo 'S';
×
185
            }
186
        }
187

NEW
188
        echo ' AFFECTING ' . count($report['messages']) . ' LINE';
×
189
        if (count($report['messages']) !== 1) {
×
190
            echo 'S';
×
191
        }
192

NEW
193
        echo "\033[0m" . PHP_EOL;
×
194

195
        foreach ($report['messages'] as $line => $lineErrors) {
×
196
            $startLine = max(($line - $surroundingLines), 1);
×
197
            $endLine   = min(($line + $surroundingLines), $lastLine);
×
198

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

211
                        $snippet .= str_repeat(' ', ($maxLineNumLength - strlen($snippetLine)));
×
NEW
212
                        $snippet .= $snippetLine . ':  ';
×
213
                        if ($snippetLine === $line) {
×
214
                            $snippet .= "\033[0m";
×
215
                        }
216
                    }
217

218
                    if (isset($tokens[$i]['orig_content']) === true) {
×
219
                        $tokenContent = $tokens[$i]['orig_content'];
×
220
                    } else {
221
                        $tokenContent = $tokens[$i]['content'];
×
222
                    }
223

224
                    if (strpos($tokenContent, "\t") !== false) {
×
225
                        $token            = $tokens[$i];
×
226
                        $token['content'] = $tokenContent;
×
227
                        if (PHP_OS_FAMILY === 'Windows') {
×
228
                            $tab = "\000";
×
229
                        } else {
230
                            $tab = "\033[30;1m»\033[0m";
×
231
                        }
232

233
                        $phpcsFile->tokenizer->replaceTabsInToken($token, $tab, "\000");
×
234
                        $tokenContent = $token['content'];
×
235
                    }
236

237
                    $tokenContent = Common::prepareForOutput($tokenContent, ["\r", "\n", "\t"]);
×
238
                    $tokenContent = str_replace("\000", ' ', $tokenContent);
×
239

240
                    $underline = false;
×
241
                    if ($snippetLine === $line && isset($lineErrors[$tokens[$i]['column']]) === true) {
×
242
                        $underline = true;
×
243
                    }
244

245
                    // Underline invisible characters as well.
246
                    if ($underline === true && trim($tokenContent) === '') {
×
NEW
247
                        $snippet .= "\033[4m" . ' ' . "\033[0m" . $tokenContent;
×
248
                    } else {
249
                        if ($underline === true) {
×
250
                            $snippet .= "\033[4m";
×
251
                        }
252

253
                        $snippet .= $tokenContent;
×
254

255
                        if ($underline === true) {
×
256
                            $snippet .= "\033[0m";
×
257
                        }
258
                    }
259
                }//end for
260
            }//end if
261

NEW
262
            echo str_repeat('-', $width) . PHP_EOL;
×
263

264
            foreach ($lineErrors as $colErrors) {
×
265
                foreach ($colErrors as $error) {
×
266
                    $padding = ($maxLineNumLength - strlen($line));
×
NEW
267
                    echo 'LINE ' . str_repeat(' ', $padding) . $line . ': ';
×
268

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

278
                    echo ' ';
×
279
                    if ($report['fixable'] > 0) {
×
280
                        echo '[';
×
281
                        if ($error['fixable'] === true) {
×
282
                            echo 'x';
×
283
                        } else {
284
                            echo ' ';
×
285
                        }
286

287
                        echo '] ';
×
288
                    }
289

290
                    $message = $error['message'];
×
NEW
291
                    $message = str_replace("\n", "\n" . $errorPadding, $message);
×
292
                    if ($showSources === true) {
×
NEW
293
                        $message = "\033[1m" . $message . "\033[0m" . ' (' . $error['source'] . ')';
×
294
                    }
295

296
                    $errorMsg = wordwrap(
×
297
                        $message,
×
298
                        $maxErrorSpace,
×
NEW
299
                        PHP_EOL . $errorPadding
×
300
                    );
×
301

NEW
302
                    echo $errorMsg . PHP_EOL;
×
303
                }//end foreach
304
            }//end foreach
305

NEW
306
            echo str_repeat('-', $width) . PHP_EOL;
×
NEW
307
            echo rtrim($snippet) . PHP_EOL;
×
308
        }//end foreach
309

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

316
        return true;
×
317

318
    }//end generateFileReport()
319

320

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

352
        echo $cachedData;
×
353

354
    }//end generate()
355

356

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