• 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/Cbf.php
1
<?php
2
/**
3
 * CBF report for PHP_CodeSniffer.
4
 *
5
 * This report implements the various auto-fixing features of the
6
 * PHPCBF script and is not intended (or allowed) to be selected as a
7
 * report from the command line.
8
 *
9
 * @author    Greg Sherwood <gsherwood@squiz.net>
10
 * @author    Juliette Reinders Folmer <phpcs_nospam@adviesenzo.nl>
11
 * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
12
 * @copyright 2025 PHPCSStandards and contributors
13
 * @license   https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
14
 */
15

16
namespace PHP_CodeSniffer\Reports;
17

18
use PHP_CodeSniffer\Exceptions\DeepExitException;
19
use PHP_CodeSniffer\Files\File;
20
use PHP_CodeSniffer\Reporter;
21
use PHP_CodeSniffer\Util\ExitCode;
22
use PHP_CodeSniffer\Util\Timing;
23
use PHP_CodeSniffer\Util\Writers\StatusWriter;
24

25
class Cbf implements Report
26
{
27

28

29
    /**
30
     * Generate a partial report for a single processed file.
31
     *
32
     * Function should return TRUE if it printed or stored data about the file
33
     * and FALSE if it ignored the file. Returning TRUE indicates that the file and
34
     * its data should be counted in the grand totals.
35
     *
36
     * @param array<string, string|int|array> $report      Prepared report data.
37
     *                                                     See the {@see Report} interface for a detailed specification.
38
     * @param \PHP_CodeSniffer\Files\File     $phpcsFile   The file being reported on.
39
     * @param bool                            $showSources Show sources?
40
     * @param int                             $width       Maximum allowed line width.
41
     *
42
     * @return bool
43
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
44
     */
45
    public function generateFileReport(array $report, File $phpcsFile, bool $showSources = false, int $width = 80)
×
46
    {
47
        $errors = $phpcsFile->getFixableCount();
×
48
        if ($errors !== 0) {
×
49
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
50
                $startTime = microtime(true);
×
51
                $newlines  = 0;
×
52
                if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
53
                    $newlines = 1;
×
54
                }
55

56
                StatusWriter::forceWrite("=> Fixing file: $errors/$errors violations remaining", 1, $newlines);
×
57
            }
58

59
            $fixed = $phpcsFile->fixer->fixFile();
×
60
        }
61

62
        if ($phpcsFile->config->stdin === true) {
×
63
            // Replacing STDIN, so output current file to STDOUT
64
            // even if nothing was fixed. Exit here because we
65
            // can't process any more than 1 file in this setup.
66
            echo $phpcsFile->fixer->getContents();
×
67

68
            // Fake a Reporter instance to allow for getting a proper exit code.
69
            $reporter = $this->createReporterInstance($phpcsFile);
×
70

71
            throw new DeepExitException('', ExitCode::calculate($reporter));
×
72
        }
73

74
        if ($errors === 0) {
×
75
            return false;
×
76
        }
77

78
        if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
79
            if ($fixed === false) {
×
80
                StatusWriter::forceWrite('ERROR', 0, 0);
×
81
            } else {
82
                StatusWriter::forceWrite('DONE', 0, 0);
×
83
            }
84

NEW
85
            StatusWriter::forceWrite(' in ' . Timing::getHumanReadableDuration(Timing::getDurationSince($startTime)));
×
86
        }
87

88
        if ($fixed === true) {
×
89
            // The filename in the report may be truncated due to a basepath setting
90
            // but we are using it for writing here and not display,
91
            // so find the correct path if basepath is in use.
NEW
92
            $newFilename = $report['filename'] . $phpcsFile->config->suffix;
×
93
            if ($phpcsFile->config->basepath !== null) {
×
NEW
94
                $newFilename = $phpcsFile->config->basepath . DIRECTORY_SEPARATOR . $newFilename;
×
95
            }
96

97
            $newContent = $phpcsFile->fixer->getContents();
×
98
            file_put_contents($newFilename, $newContent);
×
99

100
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
101
                if ($newFilename === $report['filename']) {
×
102
                    StatusWriter::forceWrite('=> File was overwritten', 1);
×
103
                } else {
NEW
104
                    StatusWriter::forceWrite('=> Fixed file written to ' . basename($newFilename), 1);
×
105
                }
106
            }
107
        }
108

109
        $errorCount   = $phpcsFile->getErrorCount();
×
110
        $warningCount = $phpcsFile->getWarningCount();
×
111
        $fixableCount = $phpcsFile->getFixableCount();
×
112
        $fixedCount   = ($errors - $fixableCount);
×
NEW
113
        echo $report['filename'] . ">>$errorCount>>$warningCount>>$fixableCount>>$fixedCount" . PHP_EOL;
×
114

115
        return $fixed;
×
116

117
    }//end generateFileReport()
118

119

120
    /**
121
     * Prints a summary of fixed files.
122
     *
123
     * @param string $cachedData    Any partial report data that was returned from
124
     *                              generateFileReport during the run.
125
     * @param int    $totalFiles    Total number of files processed during the run.
126
     * @param int    $totalErrors   Total number of errors found during the run.
127
     * @param int    $totalWarnings Total number of warnings found during the run.
128
     * @param int    $totalFixable  Total number of problems that can be fixed.
129
     * @param bool   $showSources   Show sources?
130
     * @param int    $width         Maximum allowed line width.
131
     * @param bool   $interactive   Are we running in interactive mode?
132
     * @param bool   $toScreen      Is the report being printed to screen?
133
     *
134
     * @return void
135
     */
136
    public function generate(
×
137
        string $cachedData,
138
        int $totalFiles,
139
        int $totalErrors,
140
        int $totalWarnings,
141
        int $totalFixable,
142
        bool $showSources = false,
143
        int $width = 80,
144
        bool $interactive = false,
145
        bool $toScreen = true
146
    ) {
147
        $lines = explode(PHP_EOL, $cachedData);
×
148
        array_pop($lines);
×
149

150
        if (empty($lines) === true) {
×
151
            if (($totalErrors + $totalWarnings) === 0) {
×
152
                StatusWriter::writeNewline();
×
153
                StatusWriter::write('No violations were found');
×
154
            } else {
155
                StatusWriter::writeNewline();
×
156
                StatusWriter::write('No fixable errors were found');
×
157
            }
158

159
            return;
×
160
        }
161

162
        $reportFiles = [];
×
163
        $maxLength   = 0;
×
164
        $totalFixed  = 0;
×
165
        $failures    = 0;
×
166

167
        foreach ($lines as $line) {
×
168
            $parts   = explode('>>', $line);
×
169
            $fileLen = strlen($parts[0]);
×
170
            $reportFiles[$parts[0]] = [
×
171
                'errors'   => $parts[1],
×
172
                'warnings' => $parts[2],
×
173
                'fixable'  => $parts[3],
×
174
                'fixed'    => $parts[4],
×
175
                'strlen'   => $fileLen,
×
176
            ];
177

178
            $maxLength = max($maxLength, $fileLen);
×
179

180
            $totalFixed += $parts[4];
×
181

182
            if ($parts[3] > 0) {
×
183
                $failures++;
×
184
            }
185
        }
186

187
        $width = min($width, ($maxLength + 21));
×
188
        $width = max($width, 70);
×
189

NEW
190
        echo PHP_EOL . "\033[1m" . 'PHPCBF RESULT SUMMARY' . "\033[0m" . PHP_EOL;
×
NEW
191
        echo str_repeat('-', $width) . PHP_EOL;
×
NEW
192
        echo "\033[1m" . 'FILE' . str_repeat(' ', ($width - 20)) . 'FIXED  REMAINING' . "\033[0m" . PHP_EOL;
×
NEW
193
        echo str_repeat('-', $width) . PHP_EOL;
×
194

195
        foreach ($reportFiles as $file => $data) {
×
196
            $padding = ($width - 18 - $data['strlen']);
×
197
            if ($padding < 0) {
×
NEW
198
                $file    = '...' . substr($file, (($padding * -1) + 3));
×
199
                $padding = 0;
×
200
            }
201

NEW
202
            echo $file . str_repeat(' ', $padding) . '  ';
×
203

204
            if ($data['fixable'] > 0) {
×
NEW
205
                echo "\033[31mFAILED TO FIX\033[0m" . PHP_EOL;
×
206
                continue;
×
207
            }
208

209
            $remaining = ($data['errors'] + $data['warnings']);
×
210

211
            if ($data['fixed'] !== 0) {
×
212
                echo $data['fixed'];
×
213
                echo str_repeat(' ', (7 - strlen((string) $data['fixed'])));
×
214
            } else {
215
                echo '0      ';
×
216
            }
217

218
            if ($remaining !== 0) {
×
219
                echo $remaining;
×
220
            } else {
221
                echo '0';
×
222
            }
223

224
            echo PHP_EOL;
×
225
        }//end foreach
226

NEW
227
        echo str_repeat('-', $width) . PHP_EOL;
×
228
        echo "\033[1mA TOTAL OF $totalFixed ERROR";
×
229
        if ($totalFixed !== 1) {
×
230
            echo 'S';
×
231
        }
232

233
        $numFiles = count($reportFiles);
×
NEW
234
        echo ' WERE FIXED IN ' . $numFiles . ' FILE';
×
235
        if ($numFiles !== 1) {
×
236
            echo 'S';
×
237
        }
238

239
        echo "\033[0m";
×
240

241
        if ($failures > 0) {
×
NEW
242
            echo PHP_EOL . str_repeat('-', $width) . PHP_EOL;
×
243
            echo "\033[1mPHPCBF FAILED TO FIX $failures FILE";
×
244
            if ($failures !== 1) {
×
245
                echo 'S';
×
246
            }
247

248
            echo "\033[0m";
×
249
        }
250

NEW
251
        echo PHP_EOL . str_repeat('-', $width) . PHP_EOL . PHP_EOL;
×
252

253
    }//end generate()
254

255

256
    /**
257
     * Create a "fake" Reporter instance to allow for getting a proper exit code when scanning code provided via STDIN.
258
     *
259
     * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being reported on.
260
     *
261
     * @return \PHP_CodeSniffer\Reporter
262
     */
263
    private function createReporterInstance(File $phpcsFile)
×
264
    {
265
        $reporter = new class extends Reporter {
266

267

268
            /**
269
             * Overload the constructor as we don't need it.
270
             */
271
            public function __construct()
272
            {
273
            }//end __construct()
×
274

275

276
        };
277

278
        $reporter->totalFiles           = 1;
×
279
        $reporter->totalErrors          = $phpcsFile->getFirstRunCount('error');
×
280
        $reporter->totalWarnings        = $phpcsFile->getFirstRunCount('warning');
×
281
        $reporter->totalFixableErrors   = $phpcsFile->getFixableErrorCount();
×
282
        $reporter->totalFixableWarnings = $phpcsFile->getFixableWarningCount();
×
283
        $reporter->totalFixedErrors     = $phpcsFile->getFixedErrorCount();
×
284
        $reporter->totalFixedWarnings   = $phpcsFile->getFixedWarningCount();
×
285

286
        return $reporter;
×
287

288
    }//end createReporterInstance()
289

290

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