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

PHPCSStandards / PHP_CodeSniffer / 14453527344

14 Apr 2025 06:59PM UTC coverage: 75.29% (+0.002%) from 75.288%
14453527344

push

github

web-flow
Merge pull request #987 from PHPCSStandards/phpcs-4.0/feature/689-remove-support-sniffs-breaking-naming-conventions

Ruleset: remove support for sniffs not following the naming conventions

19 of 19 new or added lines in 2 files covered. (100.0%)

1 existing line in 1 file now uncovered.

20408 of 27106 relevant lines covered (75.29%)

72.46 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

28
class Runner
29
{
30

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

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

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

52

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

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

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

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

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

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

87
                return 0;
3✔
88
            }
89

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

101
                return 0;
5✔
102
            }
103

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

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

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

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

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

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

151
    }//end runPHPCS()
152

153

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

243
    }//end runPHPCBF()
244

245

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

258
        // Ensure this option is enabled or else line endings will not always
259
        // be detected properly for files created on a Mac with the /r line ending.
260
        @ini_set('auto_detect_line_endings', true);
×
261

262
        // Disable the PCRE JIT as this caused issues with parallel running.
263
        ini_set('pcre.jit', false);
×
264

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

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

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

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

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

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

309
    }//end init()
310

311

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

324
        // Include bootstrap files.
325
        foreach ($this->config->bootstrap as $bootstrap) {
×
326
            include $bootstrap;
×
327
        }
328

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

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

348
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
349
                echo 'Creating file list... ';
×
350
            }
351

352
            $todo = new FileList($this->config, $this->ruleset);
×
353

354
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
355
                $numFiles = count($todo);
×
356
                echo "DONE ($numFiles files in queue)".PHP_EOL;
×
357
            }
358

359
            if ($this->config->cache === true) {
×
360
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
361
                    echo 'Loading cache... ';
×
362
                }
363

364
                Cache::load($this->ruleset, $this->config);
×
365

366
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
367
                    $size = Cache::getSize();
×
368
                    echo "DONE ($size files in cache)".PHP_EOL;
×
369
                }
370
            }
371
        }//end if
372

373
        // Turn all sniff errors into exceptions.
374
        set_error_handler([$this, 'handleErrors']);
×
375

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

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

387
        $lastDir  = '';
×
388
        $numFiles = count($todo);
×
389

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

401
                        $lastDir = $currDir;
×
402
                    }
403

404
                    $this->processFile($file);
×
405
                } else if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
406
                    echo 'Skipping '.basename($file->path).PHP_EOL;
×
407
                }
408

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

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

423
                $endAt = ($startAt + $numPerBatch);
×
424
                if ($endAt > $numFiles) {
×
425
                    $endAt = $numFiles;
×
426
                }
427

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

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

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

456
                        if ($file->ignored === true) {
×
457
                            $todo->next();
×
458
                            continue;
×
459
                        }
460

461
                        $currDir = dirname($path);
×
462
                        if ($lastDir !== $currDir) {
×
463
                            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
464
                                echo 'Changing into directory '.Common::stripBasepath($currDir, $this->config->basepath).PHP_EOL;
×
465
                            }
466

467
                            $lastDir = $currDir;
×
468
                        }
469

470
                        $this->processFile($file);
×
471

472
                        $pathsProcessed[] = $path;
×
473
                        $todo->next();
×
474
                    }//end for
475

476
                    $debugOutput = ob_get_contents();
×
477
                    ob_end_clean();
×
478

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

489
                    $output  = '<'.'?php'."\n".' $childOutput = ';
×
490
                    $output .= var_export($childOutput, true);
×
491
                    $output .= ";\n\$debugOutput = ";
×
492
                    $output .= var_export($debugOutput, true);
×
493

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

500
                        $output .= ";\n\$childCache = ";
×
501
                        $output .= var_export($childCache, true);
×
502
                    }
503

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

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

516
        restore_error_handler();
×
517

518
        if (PHP_CODESNIFFER_VERBOSITY === 0
×
519
            && $this->config->interactive === false
×
520
            && $this->config->showProgress === true
×
521
        ) {
522
            echo PHP_EOL.PHP_EOL;
×
523
        }
524

525
        if ($this->config->cache === true) {
×
526
            Cache::save();
×
527
        }
528

529
        $ignoreWarnings = Config::getConfigData('ignore_warnings_on_exit');
×
530
        $ignoreErrors   = Config::getConfigData('ignore_errors_on_exit');
×
531

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

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

547
        return $return;
×
548

549
    }//end run()
550

551

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

574
        throw new RuntimeException("$message in $file on line $line");
×
575

576
    }//end handleErrors()
577

578

579
    /**
580
     * Processes a single file, including checking and fixing.
581
     *
582
     * @param \PHP_CodeSniffer\Files\File $file The file to be processed.
583
     *
584
     * @return void
585
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
586
     */
587
    public function processFile($file)
×
588
    {
589
        if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
590
            $startTime = microtime(true);
×
591
            echo 'Processing '.basename($file->path).' ';
×
592
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
593
                echo PHP_EOL;
×
594
            }
595
        }
596

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

707
    }//end processFile()
708

709

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

725
        $success = true;
×
726

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

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

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

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

747
            $numProcessed++;
×
748

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

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

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

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

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

785
        return $success;
×
786

787
    }//end processChildProcs()
788

789

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

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

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

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

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

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

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

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

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

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

875
        echo $colorOpen.$progressDot.$colorClose;
60✔
876

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

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

891
        echo str_repeat(' ', $padding)." $numProcessed / $numFiles ($percent%)".PHP_EOL;
18✔
892

893
    }//end printProgress()
6✔
894

895

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

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

931
    }//end registerOutOfMemoryShutdownMessage()
932

933

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