• 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

17.55
/src/Runner.php
1
<?php
2
/**
3
 * Responsible for running PHPCS and PHPCBF.
4
 *
5
 * After creating an object of this class, you probably just want to
6
 * call runPHPCS() or runPHPCBF().
7
 *
8
 * @author    Greg Sherwood <gsherwood@squiz.net>
9
 * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
10
 * @license   https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
11
 */
12

13
namespace PHP_CodeSniffer;
14

15
use Exception;
16
use InvalidArgumentException;
17
use PHP_CodeSniffer\Exceptions\DeepExitException;
18
use PHP_CodeSniffer\Exceptions\RuntimeException;
19
use PHP_CodeSniffer\Files\DummyFile;
20
use PHP_CodeSniffer\Files\File;
21
use PHP_CodeSniffer\Files\FileList;
22
use PHP_CodeSniffer\Util\Cache;
23
use PHP_CodeSniffer\Util\Common;
24
use PHP_CodeSniffer\Util\Standards;
25
use PHP_CodeSniffer\Util\Timing;
26
use PHP_CodeSniffer\Util\Tokens;
27
use PHP_CodeSniffer\Util\Writers\StatusWriter;
28

29
class Runner
30
{
31

32
    /**
33
     * The config data for the run.
34
     *
35
     * @var \PHP_CodeSniffer\Config
36
     */
37
    public $config = null;
38

39
    /**
40
     * The ruleset used for the run.
41
     *
42
     * @var \PHP_CodeSniffer\Ruleset
43
     */
44
    public $ruleset = null;
45

46
    /**
47
     * The reporter used for generating reports after the run.
48
     *
49
     * @var \PHP_CodeSniffer\Reporter
50
     */
51
    public $reporter = null;
52

53

54
    /**
55
     * Run the PHPCS script.
56
     *
57
     * @return int
58
     */
59
    public function runPHPCS()
8✔
60
    {
61
        $this->registerOutOfMemoryShutdownMessage('phpcs');
8✔
62

63
        try {
64
            Timing::startTiming();
8✔
65

66
            if (defined('PHP_CODESNIFFER_CBF') === false) {
8✔
67
                define('PHP_CODESNIFFER_CBF', false);
×
68
            }
69

70
            // Creating the Config object populates it with all required settings
71
            // based on the CLI arguments provided to the script and any config
72
            // values the user has set.
73
            $this->config = new Config();
8✔
74

75
            // Init the run and load the rulesets to set additional config vars.
76
            $this->init();
8✔
77

78
            // Print a list of sniffs in each of the supplied standards.
79
            // We fudge the config here so that each standard is explained in isolation.
80
            if ($this->config->explain === true) {
8✔
81
                $standards = $this->config->standards;
3✔
82
                foreach ($standards as $standard) {
3✔
83
                    $this->config->standards = [$standard];
3✔
84
                    $ruleset = new Ruleset($this->config);
3✔
85
                    $ruleset->explain();
3✔
86
                }
87

88
                return 0;
3✔
89
            }
90

91
            // Generate documentation for each of the supplied standards.
92
            if ($this->config->generator !== null) {
5✔
93
                $standards = $this->config->standards;
5✔
94
                foreach ($standards as $standard) {
5✔
95
                    $this->config->standards = [$standard];
5✔
96
                    $ruleset   = new Ruleset($this->config);
5✔
97
                    $class     = 'PHP_CodeSniffer\Generators\\'.$this->config->generator;
5✔
98
                    $generator = new $class($ruleset);
5✔
99
                    $generator->generate();
5✔
100
                }
101

102
                return 0;
5✔
103
            }
104

105
            // Other report formats don't really make sense in interactive mode
106
            // so we hard-code the full report here and when outputting.
107
            // We also ensure parallel processing is off because we need to do one file at a time.
108
            if ($this->config->interactive === true) {
×
109
                $this->config->reports      = ['full' => null];
×
110
                $this->config->parallel     = 1;
×
111
                $this->config->showProgress = false;
×
112
            }
113

114
            // Disable caching if we are processing STDIN as we can't be 100%
115
            // sure where the file came from or if it will change in the future.
116
            if ($this->config->stdin === true) {
×
117
                $this->config->cache = false;
×
118
            }
119

120
            $numErrors = $this->run();
×
121

122
            // Print all the reports for this run.
123
            $toScreen = $this->reporter->printReports();
×
124

125
            // Only print timer output if no reports were
126
            // printed to the screen so we don't put additional output
127
            // in something like an XML report. If we are printing to screen,
128
            // the report types would have already worked out who should
129
            // print the timer info.
130
            if ($this->config->interactive === false
×
131
                && ($toScreen === false
×
132
                || (($this->reporter->totalErrors + $this->reporter->totalWarnings) === 0 && $this->config->showProgress === true))
×
133
            ) {
134
                Timing::printRunTime();
×
135
            }
136
        } catch (DeepExitException $e) {
×
137
            echo $e->getMessage();
×
138
            return $e->getCode();
×
139
        }//end try
140

141
        if ($numErrors === 0) {
×
142
            // No errors found.
143
            return 0;
×
144
        } else if ($this->reporter->totalFixable === 0) {
×
145
            // Errors found, but none of them can be fixed by PHPCBF.
146
            return 1;
×
147
        } else {
148
            // Errors found, and some can be fixed by PHPCBF.
149
            return 2;
×
150
        }
151

152
    }//end runPHPCS()
153

154

155
    /**
156
     * Run the PHPCBF script.
157
     *
158
     * @return int
159
     */
160
    public function runPHPCBF()
×
161
    {
162
        $this->registerOutOfMemoryShutdownMessage('phpcbf');
×
163

164
        if (defined('PHP_CODESNIFFER_CBF') === false) {
×
165
            define('PHP_CODESNIFFER_CBF', true);
×
166
        }
167

168
        try {
169
            Timing::startTiming();
×
170

171
            // Creating the Config object populates it with all required settings
172
            // based on the CLI arguments provided to the script and any config
173
            // values the user has set.
174
            $this->config = new Config();
×
175

176
            // When processing STDIN, we can't output anything to the screen
177
            // or it will end up mixed in with the file output.
178
            if ($this->config->stdin === true) {
×
179
                $this->config->verbosity = 0;
×
180
            }
181

182
            // Init the run and load the rulesets to set additional config vars.
183
            $this->init();
×
184

185
            // When processing STDIN, we only process one file at a time and
186
            // we don't process all the way through, so we can't use the parallel
187
            // running system.
188
            if ($this->config->stdin === true) {
×
189
                $this->config->parallel = 1;
×
190
            }
191

192
            // Override some of the command line settings that might break the fixes.
193
            $this->config->generator    = null;
×
194
            $this->config->explain      = false;
×
195
            $this->config->interactive  = false;
×
196
            $this->config->cache        = false;
×
197
            $this->config->showSources  = false;
×
198
            $this->config->recordErrors = false;
×
199
            $this->config->reportFile   = null;
×
200

201
            // Only use the "Cbf" report, but allow for the Performance report as well.
202
            $originalReports = array_change_key_case($this->config->reports, CASE_LOWER);
×
203
            $newReports      = ['cbf' => null];
×
204
            if (array_key_exists('performance', $originalReports) === true) {
×
205
                $newReports['performance'] = $originalReports['performance'];
×
206
            }
207

208
            $this->config->reports = $newReports;
×
209

210
            // If a standard tries to set command line arguments itself, some
211
            // may be blocked because PHPCBF is running, so stop the script
212
            // dying if any are found.
213
            $this->config->dieOnUnknownArg = false;
×
214

215
            $this->run();
×
216
            $this->reporter->printReports();
×
217

218
            echo PHP_EOL;
×
219
            Timing::printRunTime();
×
220
        } catch (DeepExitException $e) {
×
221
            echo $e->getMessage();
×
222
            return $e->getCode();
×
223
        }//end try
224

225
        if ($this->reporter->totalFixed === 0) {
×
226
            // Nothing was fixed by PHPCBF.
227
            if ($this->reporter->totalFixable === 0) {
×
228
                // Nothing found that could be fixed.
229
                return 0;
×
230
            } else {
231
                // Something failed to fix.
232
                return 2;
×
233
            }
234
        }
235

236
        if ($this->reporter->totalFixable === 0) {
×
237
            // PHPCBF fixed all fixable errors.
238
            return 1;
×
239
        }
240

241
        // PHPCBF fixed some fixable errors, but others failed to fix.
242
        return 2;
×
243

244
    }//end runPHPCBF()
245

246

247
    /**
248
     * Init the rulesets and other high-level settings.
249
     *
250
     * @return void
251
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If a referenced standard is not installed.
252
     */
253
    public function init()
×
254
    {
255
        if (defined('PHP_CODESNIFFER_CBF') === false) {
×
256
            define('PHP_CODESNIFFER_CBF', false);
×
257
        }
258

259
        // Disable the PCRE JIT as this caused issues with parallel running.
260
        ini_set('pcre.jit', false);
×
261

262
        // Check that the standards are valid.
263
        foreach ($this->config->standards as $standard) {
×
264
            if (Standards::isInstalledStandard($standard) === false) {
×
265
                // They didn't select a valid coding standard, so help them
266
                // out by letting them know which standards are installed.
267
                $error = 'ERROR: the "'.$standard.'" coding standard is not installed. ';
×
268
                ob_start();
×
269
                Standards::printInstalledStandards();
×
270
                $error .= ob_get_contents();
×
271
                ob_end_clean();
×
272
                throw new DeepExitException($error, 3);
×
273
            }
274
        }
275

276
        // Saves passing the Config object into other objects that only need
277
        // the verbosity flag for debug output.
278
        if (defined('PHP_CODESNIFFER_VERBOSITY') === false) {
×
279
            define('PHP_CODESNIFFER_VERBOSITY', $this->config->verbosity);
×
280
        }
281

282
        // Create this class so it is autoloaded and sets up a bunch
283
        // of PHP_CodeSniffer-specific token type constants.
284
        new Tokens();
×
285

286
        // Allow autoloading of custom files inside installed standards.
287
        $installedStandards = Standards::getInstalledStandardDetails();
×
288
        foreach ($installedStandards as $details) {
×
289
            Autoload::addSearchPath($details['path'], $details['namespace']);
×
290
        }
291

292
        // The ruleset contains all the information about how the files
293
        // should be checked and/or fixed.
294
        try {
295
            $this->ruleset = new Ruleset($this->config);
×
296

297
            if ($this->ruleset->hasSniffDeprecations() === true) {
×
298
                $this->ruleset->showSniffDeprecations();
×
299
            }
300
        } catch (RuntimeException $e) {
×
301
            $error  = rtrim($e->getMessage(), "\r\n").PHP_EOL.PHP_EOL;
×
302
            $error .= $this->config->printShortUsage(true);
×
303
            throw new DeepExitException($error, 3);
×
304
        }
305

306
    }//end init()
307

308

309
    /**
310
     * Performs the run.
311
     *
312
     * @return int The number of errors and warnings found.
313
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
314
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException
315
     */
316
    private function run()
×
317
    {
318
        // The class that manages all reporters for the run.
319
        $this->reporter = new Reporter($this->config);
×
320

321
        // Include bootstrap files.
322
        foreach ($this->config->bootstrap as $bootstrap) {
×
323
            include $bootstrap;
×
324
        }
325

326
        if ($this->config->stdin === true) {
×
327
            $fileContents = $this->config->stdinContent;
×
328
            if ($fileContents === null) {
×
329
                $handle = fopen('php://stdin', 'r');
×
330
                stream_set_blocking($handle, true);
×
331
                $fileContents = stream_get_contents($handle);
×
332
                fclose($handle);
×
333
            }
334

335
            $todo  = new FileList($this->config, $this->ruleset);
×
336
            $dummy = new DummyFile($fileContents, $this->ruleset, $this->config);
×
337
            $todo->addFile($dummy->path, $dummy);
×
338
        } else {
339
            if (empty($this->config->files) === true) {
×
340
                $error  = 'ERROR: You must supply at least one file or directory to process.'.PHP_EOL.PHP_EOL;
×
341
                $error .= $this->config->printShortUsage(true);
×
342
                throw new DeepExitException($error, 3);
×
343
            }
344

345
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
NEW
346
                StatusWriter::write('Creating file list... ', 0, 0);
×
347
            }
348

349
            $todo = new FileList($this->config, $this->ruleset);
×
350

351
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
352
                $numFiles = count($todo);
×
NEW
353
                StatusWriter::write("DONE ($numFiles files in queue)");
×
354
            }
355

356
            if ($this->config->cache === true) {
×
357
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
NEW
358
                    StatusWriter::write('Loading cache... ', 0, 0);
×
359
                }
360

361
                Cache::load($this->ruleset, $this->config);
×
362

363
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
364
                    $size = Cache::getSize();
×
NEW
365
                    StatusWriter::write("DONE ($size files in cache)");
×
366
                }
367
            }
368
        }//end if
369

370
        // Turn all sniff errors into exceptions.
371
        set_error_handler([$this, 'handleErrors']);
×
372

373
        // If verbosity is too high, turn off parallelism so the
374
        // debug output is clean.
375
        if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
376
            $this->config->parallel = 1;
×
377
        }
378

379
        // If the PCNTL extension isn't installed, we can't fork.
380
        if (function_exists('pcntl_fork') === false) {
×
381
            $this->config->parallel = 1;
×
382
        }
383

384
        $lastDir  = '';
×
385
        $numFiles = count($todo);
×
386

387
        if ($this->config->parallel === 1) {
×
388
            // Running normally.
389
            $numProcessed = 0;
×
390
            foreach ($todo as $path => $file) {
×
391
                if ($file->ignored === false) {
×
392
                    $currDir = dirname($path);
×
393
                    if ($lastDir !== $currDir) {
×
394
                        if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
NEW
395
                            StatusWriter::write('Changing into directory '.Common::stripBasepath($currDir, $this->config->basepath));
×
396
                        }
397

398
                        $lastDir = $currDir;
×
399
                    }
400

401
                    $this->processFile($file);
×
402
                } else if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
NEW
403
                    StatusWriter::write('Skipping '.basename($file->path));
×
404
                }
405

406
                $numProcessed++;
×
407
                $this->printProgress($file, $numFiles, $numProcessed);
×
408
            }
409
        } else {
410
            // Batching and forking.
411
            $childProcs  = [];
×
412
            $numPerBatch = ceil($numFiles / $this->config->parallel);
×
413

414
            for ($batch = 0; $batch < $this->config->parallel; $batch++) {
×
415
                $startAt = ($batch * $numPerBatch);
×
416
                if ($startAt >= $numFiles) {
×
417
                    break;
×
418
                }
419

420
                $endAt = ($startAt + $numPerBatch);
×
421
                if ($endAt > $numFiles) {
×
422
                    $endAt = $numFiles;
×
423
                }
424

425
                $childOutFilename = tempnam(sys_get_temp_dir(), 'phpcs-child');
×
426
                $pid = pcntl_fork();
×
427
                if ($pid === -1) {
×
428
                    throw new RuntimeException('Failed to create child process');
×
429
                } else if ($pid !== 0) {
×
430
                    $childProcs[$pid] = $childOutFilename;
×
431
                } else {
432
                    // Move forward to the start of the batch.
433
                    $todo->rewind();
×
434
                    for ($i = 0; $i < $startAt; $i++) {
×
435
                        $todo->next();
×
436
                    }
437

438
                    // Reset the reporter to make sure only figures from this
439
                    // file batch are recorded.
440
                    $this->reporter->totalFiles    = 0;
×
441
                    $this->reporter->totalErrors   = 0;
×
442
                    $this->reporter->totalWarnings = 0;
×
443
                    $this->reporter->totalFixable  = 0;
×
444
                    $this->reporter->totalFixed    = 0;
×
445

446
                    // Process the files.
447
                    $pathsProcessed = [];
×
448
                    ob_start();
×
449
                    for ($i = $startAt; $i < $endAt; $i++) {
×
450
                        $path = $todo->key();
×
451
                        $file = $todo->current();
×
452

453
                        if ($file->ignored === true) {
×
454
                            $todo->next();
×
455
                            continue;
×
456
                        }
457

458
                        $currDir = dirname($path);
×
459
                        if ($lastDir !== $currDir) {
×
460
                            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
NEW
461
                                StatusWriter::write('Changing into directory '.Common::stripBasepath($currDir, $this->config->basepath));
×
462
                            }
463

464
                            $lastDir = $currDir;
×
465
                        }
466

467
                        $this->processFile($file);
×
468

469
                        $pathsProcessed[] = $path;
×
470
                        $todo->next();
×
471
                    }//end for
472

473
                    $debugOutput = ob_get_contents();
×
474
                    ob_end_clean();
×
475

476
                    // Write information about the run to the filesystem
477
                    // so it can be picked up by the main process.
478
                    $childOutput = [
479
                        'totalFiles'    => $this->reporter->totalFiles,
×
480
                        'totalErrors'   => $this->reporter->totalErrors,
×
481
                        'totalWarnings' => $this->reporter->totalWarnings,
×
482
                        'totalFixable'  => $this->reporter->totalFixable,
×
483
                        'totalFixed'    => $this->reporter->totalFixed,
×
484
                    ];
485

486
                    $output  = '<'.'?php'."\n".' $childOutput = ';
×
487
                    $output .= var_export($childOutput, true);
×
488
                    $output .= ";\n\$debugOutput = ";
×
489
                    $output .= var_export($debugOutput, true);
×
490

491
                    if ($this->config->cache === true) {
×
492
                        $childCache = [];
×
493
                        foreach ($pathsProcessed as $path) {
×
494
                            $childCache[$path] = Cache::get($path);
×
495
                        }
496

497
                        $output .= ";\n\$childCache = ";
×
498
                        $output .= var_export($childCache, true);
×
499
                    }
500

501
                    $output .= ";\n?".'>';
×
502
                    file_put_contents($childOutFilename, $output);
×
503
                    exit();
×
504
                }//end if
505
            }//end for
506

507
            $success = $this->processChildProcs($childProcs);
×
508
            if ($success === false) {
×
509
                throw new RuntimeException('One or more child processes failed to run');
×
510
            }
511
        }//end if
512

513
        restore_error_handler();
×
514

515
        if (PHP_CODESNIFFER_VERBOSITY === 0
×
516
            && $this->config->interactive === false
×
517
            && $this->config->showProgress === true
×
518
        ) {
NEW
519
            StatusWriter::writeNewline(2);
×
520
        }
521

522
        if ($this->config->cache === true) {
×
523
            Cache::save();
×
524
        }
525

526
        $ignoreWarnings = Config::getConfigData('ignore_warnings_on_exit');
×
527
        $ignoreErrors   = Config::getConfigData('ignore_errors_on_exit');
×
528

529
        $return = ($this->reporter->totalErrors + $this->reporter->totalWarnings);
×
530
        if ($ignoreErrors !== null) {
×
531
            $ignoreErrors = (bool) $ignoreErrors;
×
532
            if ($ignoreErrors === true) {
×
533
                $return -= $this->reporter->totalErrors;
×
534
            }
535
        }
536

537
        if ($ignoreWarnings !== null) {
×
538
            $ignoreWarnings = (bool) $ignoreWarnings;
×
539
            if ($ignoreWarnings === true) {
×
540
                $return -= $this->reporter->totalWarnings;
×
541
            }
542
        }
543

544
        return $return;
×
545

546
    }//end run()
547

548

549
    /**
550
     * Converts all PHP errors into exceptions.
551
     *
552
     * This method forces a sniff to stop processing if it is not
553
     * able to handle a specific piece of code, instead of continuing
554
     * and potentially getting into a loop.
555
     *
556
     * @param int    $code    The level of error raised.
557
     * @param string $message The error message.
558
     * @param string $file    The path of the file that raised the error.
559
     * @param int    $line    The line number the error was raised at.
560
     *
561
     * @return bool
562
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException
563
     */
564
    public function handleErrors($code, $message, $file, $line)
×
565
    {
566
        if ((error_reporting() & $code) === 0) {
×
567
            // This type of error is being muted.
568
            return true;
×
569
        }
570

571
        throw new RuntimeException("$message in $file on line $line");
×
572

573
    }//end handleErrors()
574

575

576
    /**
577
     * Processes a single file, including checking and fixing.
578
     *
579
     * @param \PHP_CodeSniffer\Files\File $file The file to be processed.
580
     *
581
     * @return void
582
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
583
     */
584
    public function processFile($file)
×
585
    {
586
        if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
587
            $startTime = microtime(true);
×
NEW
588
            $newlines  = 0;
×
589
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
NEW
590
                $newlines = 1;
×
591
            }
592

NEW
593
            StatusWriter::write('Processing '.basename($file->path).' ', 0, $newlines);
×
594
        }
595

596
        try {
597
            $file->process();
×
598

599
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
600
                $timeTaken = ((microtime(true) - $startTime) * 1000);
×
601
                if ($timeTaken < 1000) {
×
602
                    $timeTaken = round($timeTaken);
×
NEW
603
                    StatusWriter::write("DONE in {$timeTaken}ms", 0, 0);
×
604
                } else {
605
                    $timeTaken = round(($timeTaken / 1000), 2);
×
NEW
606
                    StatusWriter::write("DONE in $timeTaken secs", 0, 0);
×
607
                }
608

609
                if (PHP_CODESNIFFER_CBF === true) {
×
610
                    $errors = $file->getFixableCount();
×
NEW
611
                    StatusWriter::write(" ($errors fixable violations)");
×
612
                } else {
613
                    $errors   = $file->getErrorCount();
×
614
                    $warnings = $file->getWarningCount();
×
NEW
615
                    StatusWriter::write(" ($errors errors, $warnings warnings)");
×
616
                }
617
            }
618
        } catch (Exception $e) {
×
619
            $error = 'An error occurred during processing; checking has been aborted. The error message was: '.$e->getMessage();
×
620

621
            // Determine which sniff caused the error.
622
            $sniffStack = null;
×
623
            $nextStack  = null;
×
624
            foreach ($e->getTrace() as $step) {
×
625
                if (isset($step['file']) === false) {
×
626
                    continue;
×
627
                }
628

629
                if (empty($sniffStack) === false) {
×
630
                    $nextStack = $step;
×
631
                    break;
×
632
                }
633

634
                if (substr($step['file'], -9) === 'Sniff.php') {
×
635
                    $sniffStack = $step;
×
636
                    continue;
×
637
                }
638
            }
639

640
            if (empty($sniffStack) === false) {
×
641
                $sniffCode = '';
×
642
                try {
643
                    if (empty($nextStack) === false
×
644
                        && isset($nextStack['class']) === true
×
645
                    ) {
646
                        $sniffCode = 'the '.Common::getSniffCode($nextStack['class']).' sniff';
×
647
                    }
648
                } catch (InvalidArgumentException $e) {
×
649
                    // Sniff code could not be determined. This may be an abstract sniff class.
650
                }
651

652
                if ($sniffCode === '') {
×
653
                    $sniffCode = substr(strrchr(str_replace('\\', '/', $sniffStack['file']), '/'), 1);
×
654
                }
655

656
                $error .= sprintf(PHP_EOL.'The error originated in %s on line %s.', $sniffCode, $sniffStack['line']);
×
657
            }
658

659
            $file->addErrorOnLine($error, 1, 'Internal.Exception');
×
660
        }//end try
661

662
        $this->reporter->cacheFileReport($file);
×
663

664
        if ($this->config->interactive === true) {
×
665
            /*
666
                Running interactively.
667
                Print the error report for the current file and then wait for user input.
668
            */
669

670
            // Get current violations and then clear the list to make sure
671
            // we only print violations for a single file each time.
672
            $numErrors = null;
×
673
            while ($numErrors !== 0) {
×
674
                $numErrors = ($file->getErrorCount() + $file->getWarningCount());
×
675
                if ($numErrors === 0) {
×
676
                    continue;
×
677
                }
678

679
                $this->reporter->printReport('full');
×
680

681
                echo '<ENTER> to recheck, [s] to skip or [q] to quit : ';
×
682
                $input = fgets(STDIN);
×
683
                $input = trim($input);
×
684

685
                switch ($input) {
686
                case 's':
×
687
                    break(2);
×
688
                case 'q':
×
689
                    throw new DeepExitException('', 0);
×
690
                default:
691
                    // Repopulate the sniffs because some of them save their state
692
                    // and only clear it when the file changes, but we are rechecking
693
                    // the same file.
694
                    $file->ruleset->populateTokenListeners();
×
695
                    $file->reloadContent();
×
696
                    $file->process();
×
697
                    $this->reporter->cacheFileReport($file);
×
698
                    break;
×
699
                }
700
            }//end while
701
        }//end if
702

703
        // Clean up the file to save (a lot of) memory.
704
        $file->cleanUp();
×
705

706
    }//end processFile()
707

708

709
    /**
710
     * Waits for child processes to complete and cleans up after them.
711
     *
712
     * The reporting information returned by each child process is merged
713
     * into the main reporter class.
714
     *
715
     * @param array $childProcs An array of child processes to wait for.
716
     *
717
     * @return bool
718
     */
719
    private function processChildProcs($childProcs)
×
720
    {
721
        $numProcessed = 0;
×
722
        $totalBatches = count($childProcs);
×
723

724
        $success = true;
×
725

726
        while (count($childProcs) > 0) {
×
727
            $pid = pcntl_waitpid(0, $status);
×
728
            if ($pid <= 0) {
×
729
                continue;
×
730
            }
731

732
            $childProcessStatus = pcntl_wexitstatus($status);
×
733
            if ($childProcessStatus !== 0) {
×
734
                $success = false;
×
735
            }
736

737
            $out = $childProcs[$pid];
×
738
            unset($childProcs[$pid]);
×
739
            if (file_exists($out) === false) {
×
740
                continue;
×
741
            }
742

743
            include $out;
×
744
            unlink($out);
×
745

746
            $numProcessed++;
×
747

748
            if (isset($childOutput) === false) {
×
749
                // The child process died, so the run has failed.
750
                $file = new DummyFile('', $this->ruleset, $this->config);
×
751
                $file->setErrorCounts(1, 0, 0, 0);
×
752
                $this->printProgress($file, $totalBatches, $numProcessed);
×
753
                $success = false;
×
754
                continue;
×
755
            }
756

757
            $this->reporter->totalFiles    += $childOutput['totalFiles'];
×
758
            $this->reporter->totalErrors   += $childOutput['totalErrors'];
×
759
            $this->reporter->totalWarnings += $childOutput['totalWarnings'];
×
760
            $this->reporter->totalFixable  += $childOutput['totalFixable'];
×
761
            $this->reporter->totalFixed    += $childOutput['totalFixed'];
×
762

763
            if (isset($debugOutput) === true) {
×
764
                echo $debugOutput;
×
765
            }
766

767
            if (isset($childCache) === true) {
×
768
                foreach ($childCache as $path => $cache) {
×
769
                    Cache::set($path, $cache);
×
770
                }
771
            }
772

773
            // Fake a processed file so we can print progress output for the batch.
774
            $file = new DummyFile('', $this->ruleset, $this->config);
×
775
            $file->setErrorCounts(
×
776
                $childOutput['totalErrors'],
×
777
                $childOutput['totalWarnings'],
×
778
                $childOutput['totalFixable'],
×
779
                $childOutput['totalFixed']
×
780
            );
781
            $this->printProgress($file, $totalBatches, $numProcessed);
×
782
        }//end while
783

784
        return $success;
×
785

786
    }//end processChildProcs()
787

788

789
    /**
790
     * Print progress information for a single processed file.
791
     *
792
     * @param \PHP_CodeSniffer\Files\File $file         The file that was processed.
793
     * @param int                         $numFiles     The total number of files to process.
794
     * @param int                         $numProcessed The number of files that have been processed,
795
     *                                                  including this one.
796
     *
797
     * @return void
798
     */
799
    public function printProgress(File $file, $numFiles, $numProcessed)
63✔
800
    {
801
        if (PHP_CODESNIFFER_VERBOSITY > 0
63✔
802
            || $this->config->showProgress === false
63✔
803
        ) {
804
            return;
3✔
805
        }
806

807
        $showColors  = $this->config->colors;
60✔
808
        $colorOpen   = '';
60✔
809
        $progressDot = '.';
60✔
810
        $colorClose  = '';
60✔
811

812
        // Show progress information.
813
        if ($file->ignored === true) {
60✔
814
            $progressDot = 'S';
3✔
815
        } else {
816
            $errors   = $file->getErrorCount();
60✔
817
            $warnings = $file->getWarningCount();
60✔
818
            $fixable  = $file->getFixableCount();
60✔
819
            $fixed    = $file->getFixedCount();
60✔
820

821
            if (PHP_CODESNIFFER_CBF === true) {
60✔
822
                // Files with fixed errors or warnings are F (green).
823
                // Files with unfixable errors or warnings are E (red).
824
                // Files with no errors or warnings are . (black).
825
                if ($fixable > 0) {
18✔
826
                    $progressDot = 'E';
6✔
827

828
                    if ($showColors === true) {
6✔
829
                        $colorOpen  = "\033[31m";
3✔
830
                        $colorClose = "\033[0m";
5✔
831
                    }
832
                } else if ($fixed > 0) {
12✔
833
                    $progressDot = 'F';
6✔
834

835
                    if ($showColors === true) {
6✔
836
                        $colorOpen  = "\033[32m";
3✔
837
                        $colorClose = "\033[0m";
13✔
838
                    }
839
                }//end if
840
            } else {
841
                // Files with errors are E (red).
842
                // Files with fixable errors are E (green).
843
                // Files with warnings are W (yellow).
844
                // Files with fixable warnings are W (green).
845
                // Files with no errors or warnings are . (black).
846
                if ($errors > 0) {
42✔
847
                    $progressDot = 'E';
9✔
848

849
                    if ($showColors === true) {
9✔
850
                        if ($fixable > 0) {
6✔
851
                            $colorOpen = "\033[32m";
3✔
852
                        } else {
853
                            $colorOpen = "\033[31m";
3✔
854
                        }
855

856
                        $colorClose = "\033[0m";
8✔
857
                    }
858
                } else if ($warnings > 0) {
33✔
859
                    $progressDot = 'W';
9✔
860

861
                    if ($showColors === true) {
9✔
862
                        if ($fixable > 0) {
6✔
863
                            $colorOpen = "\033[32m";
3✔
864
                        } else {
865
                            $colorOpen = "\033[33m";
3✔
866
                        }
867

868
                        $colorClose = "\033[0m";
6✔
869
                    }
870
                }//end if
871
            }//end if
872
        }//end if
873

874
        StatusWriter::write($colorOpen.$progressDot.$colorClose, 0, 0);
60✔
875

876
        $numPerLine = 60;
60✔
877
        if ($numProcessed !== $numFiles && ($numProcessed % $numPerLine) !== 0) {
60✔
878
            return;
60✔
879
        }
880

881
        $percent = round(($numProcessed / $numFiles) * 100);
18✔
882
        $padding = (strlen($numFiles) - strlen($numProcessed));
18✔
883
        if ($numProcessed === $numFiles
18✔
884
            && $numFiles > $numPerLine
18✔
885
            && ($numProcessed % $numPerLine) !== 0
18✔
886
        ) {
887
            $padding += ($numPerLine - ($numFiles - (floor($numFiles / $numPerLine) * $numPerLine)));
9✔
888
        }
889

890
        StatusWriter::write(str_repeat(' ', $padding)." $numProcessed / $numFiles ($percent%)");
18✔
891

892
    }//end printProgress()
6✔
893

894

895
    /**
896
     * Registers a PHP shutdown function to provide a more informative out of memory error.
897
     *
898
     * @param string $command The command which was used to initiate the PHPCS run.
899
     *
900
     * @return void
901
     */
902
    private function registerOutOfMemoryShutdownMessage($command)
×
903
    {
904
        // Allocate all needed memory beforehand as much as possible.
905
        $errorMsg    = PHP_EOL.'The PHP_CodeSniffer "%1$s" command ran out of memory.'.PHP_EOL;
×
906
        $errorMsg   .= 'Either raise the "memory_limit" of PHP in the php.ini file or raise the memory limit at runtime'.PHP_EOL;
×
907
        $errorMsg   .= 'using `%1$s -d memory_limit=512M` (replace 512M with the desired memory limit).'.PHP_EOL;
×
908
        $errorMsg    = sprintf($errorMsg, $command);
×
909
        $memoryError = 'Allowed memory size of';
×
910
        $errorArray  = [
911
            'type'    => 42,
×
912
            'message' => 'Some random dummy string to take up memory and take up some more memory and some more',
913
            'file'    => 'Another random string, which would be a filename this time. Should be relatively long to allow for deeply nested files',
914
            'line'    => 31427,
915
        ];
916

917
        register_shutdown_function(
×
918
            static function () use (
919
                $errorMsg,
×
920
                $memoryError,
×
921
                $errorArray
×
922
            ) {
923
                $errorArray = error_get_last();
×
924
                if (is_array($errorArray) === true && strpos($errorArray['message'], $memoryError) !== false) {
×
NEW
925
                    fwrite(STDERR, $errorMsg);
×
926
                }
927
            }
×
928
        );
929

930
    }//end registerOutOfMemoryShutdownMessage()
931

932

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