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

PHPCSStandards / PHP_CodeSniffer / 14467325770

15 Apr 2025 10:35AM UTC coverage: 77.621% (+0.004%) from 77.617%
14467325770

push

github

web-flow
Merge pull request #992 from PHPCSStandards/phpcs-4.0/feature/sq-3394-remove-use-of-auto_detect_line_endings

Runner: removed use of deprecated auto_detect_line_endings ini setting

19364 of 24947 relevant lines covered (77.62%)

78.59 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

17.59
/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
        // Disable the PCRE JIT as this caused issues with parallel running.
259
        ini_set('pcre.jit', false);
×
260

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

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

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

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

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

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

305
    }//end init()
306

307

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

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

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

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

344
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
345
                echo 'Creating file list... ';
×
346
            }
347

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

350
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
351
                $numFiles = count($todo);
×
352
                echo "DONE ($numFiles files in queue)".PHP_EOL;
×
353
            }
354

355
            if ($this->config->cache === true) {
×
356
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
357
                    echo 'Loading cache... ';
×
358
                }
359

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

362
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
363
                    $size = Cache::getSize();
×
364
                    echo "DONE ($size files in cache)".PHP_EOL;
×
365
                }
366
            }
367
        }//end if
368

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

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

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

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

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

397
                        $lastDir = $currDir;
×
398
                    }
399

400
                    $this->processFile($file);
×
401
                } else if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
402
                    echo 'Skipping '.basename($file->path).PHP_EOL;
×
403
                }
404

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

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

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

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

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

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

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

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

463
                            $lastDir = $currDir;
×
464
                        }
465

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

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

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

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

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

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

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

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

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

512
        restore_error_handler();
×
513

514
        if (PHP_CODESNIFFER_VERBOSITY === 0
×
515
            && $this->config->interactive === false
×
516
            && $this->config->showProgress === true
×
517
        ) {
518
            echo PHP_EOL.PHP_EOL;
×
519
        }
520

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

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

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

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

543
        return $return;
×
544

545
    }//end run()
546

547

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

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

572
    }//end handleErrors()
573

574

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

593
        try {
594
            $file->process();
×
595

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

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

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

626
                if (empty($sniffStack) === false) {
×
627
                    $nextStack = $step;
×
628
                    break;
×
629
                }
630

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

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

649
                if ($sniffCode === '') {
×
650
                    $sniffCode = substr(strrchr(str_replace('\\', '/', $sniffStack['file']), '/'), 1);
×
651
                }
652

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

656
            $file->addErrorOnLine($error, 1, 'Internal.Exception');
×
657
        }//end try
658

659
        $this->reporter->cacheFileReport($file);
×
660

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

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

676
                $this->reporter->printReport('full');
×
677

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

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

700
        // Clean up the file to save (a lot of) memory.
701
        $file->cleanUp();
×
702

703
    }//end processFile()
704

705

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

721
        $success = true;
×
722

723
        while (count($childProcs) > 0) {
×
724
            $pid = pcntl_waitpid(0, $status);
×
725
            if ($pid <= 0) {
×
726
                continue;
×
727
            }
728

729
            $childProcessStatus = pcntl_wexitstatus($status);
×
730
            if ($childProcessStatus !== 0) {
×
731
                $success = false;
×
732
            }
733

734
            $out = $childProcs[$pid];
×
735
            unset($childProcs[$pid]);
×
736
            if (file_exists($out) === false) {
×
737
                continue;
×
738
            }
739

740
            include $out;
×
741
            unlink($out);
×
742

743
            $numProcessed++;
×
744

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

754
            $this->reporter->totalFiles    += $childOutput['totalFiles'];
×
755
            $this->reporter->totalErrors   += $childOutput['totalErrors'];
×
756
            $this->reporter->totalWarnings += $childOutput['totalWarnings'];
×
757
            $this->reporter->totalFixable  += $childOutput['totalFixable'];
×
758
            $this->reporter->totalFixed    += $childOutput['totalFixed'];
×
759

760
            if (isset($debugOutput) === true) {
×
761
                echo $debugOutput;
×
762
            }
763

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

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

781
        return $success;
×
782

783
    }//end processChildProcs()
784

785

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

804
        $showColors  = $this->config->colors;
60✔
805
        $colorOpen   = '';
60✔
806
        $progressDot = '.';
60✔
807
        $colorClose  = '';
60✔
808

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

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

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

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

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

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

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

865
                        $colorClose = "\033[0m";
6✔
866
                    }
867
                }//end if
868
            }//end if
869
        }//end if
870

871
        echo $colorOpen.$progressDot.$colorClose;
60✔
872

873
        $numPerLine = 60;
60✔
874
        if ($numProcessed !== $numFiles && ($numProcessed % $numPerLine) !== 0) {
60✔
875
            return;
60✔
876
        }
877

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

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

889
    }//end printProgress()
6✔
890

891

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

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

927
    }//end registerOutOfMemoryShutdownMessage()
928

929

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