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

PHPCSStandards / PHP_CodeSniffer / 14516694961

17 Apr 2025 01:22PM UTC coverage: 77.992% (+0.05%) from 77.945%
14516694961

push

github

web-flow
Merge pull request #1011 from PHPCSStandards/phpcs-4.0/feature/always-display-runtime-info

Always display timing after run, except when in quiet mode

0 of 5 new or added lines in 1 file covered. (0.0%)

1 existing line in 1 file now uncovered.

19455 of 24945 relevant lines covered (77.99%)

78.68 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
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.
NEW
123
            $this->reporter->printReports();
×
124

NEW
125
            if ($this->config->quiet === false) {
×
UNCOV
126
                Timing::printRunTime();
×
127
            }
128
        } catch (DeepExitException $e) {
×
129
            echo $e->getMessage();
×
130
            return $e->getCode();
×
131
        }//end try
132

133
        if ($numErrors === 0) {
×
134
            // No errors found.
135
            return 0;
×
136
        } else if ($this->reporter->totalFixable === 0) {
×
137
            // Errors found, but none of them can be fixed by PHPCBF.
138
            return 1;
×
139
        } else {
140
            // Errors found, and some can be fixed by PHPCBF.
141
            return 2;
×
142
        }
143

144
    }//end runPHPCS()
145

146

147
    /**
148
     * Run the PHPCBF script.
149
     *
150
     * @return int
151
     */
152
    public function runPHPCBF()
×
153
    {
154
        $this->registerOutOfMemoryShutdownMessage('phpcbf');
×
155

156
        if (defined('PHP_CODESNIFFER_CBF') === false) {
×
157
            define('PHP_CODESNIFFER_CBF', true);
×
158
        }
159

160
        try {
161
            Timing::startTiming();
×
162

163
            // Creating the Config object populates it with all required settings
164
            // based on the CLI arguments provided to the script and any config
165
            // values the user has set.
166
            $this->config = new Config();
×
167

168
            // When processing STDIN, we can't output anything to the screen
169
            // or it will end up mixed in with the file output.
170
            if ($this->config->stdin === true) {
×
171
                $this->config->verbosity = 0;
×
172
            }
173

174
            // Init the run and load the rulesets to set additional config vars.
175
            $this->init();
×
176

177
            // When processing STDIN, we only process one file at a time and
178
            // we don't process all the way through, so we can't use the parallel
179
            // running system.
180
            if ($this->config->stdin === true) {
×
181
                $this->config->parallel = 1;
×
182
            }
183

184
            // Override some of the command line settings that might break the fixes.
185
            $this->config->generator    = null;
×
186
            $this->config->explain      = false;
×
187
            $this->config->interactive  = false;
×
188
            $this->config->cache        = false;
×
189
            $this->config->showSources  = false;
×
190
            $this->config->recordErrors = false;
×
191
            $this->config->reportFile   = null;
×
192

193
            // Only use the "Cbf" report, but allow for the Performance report as well.
194
            $originalReports = array_change_key_case($this->config->reports, CASE_LOWER);
×
195
            $newReports      = ['cbf' => null];
×
196
            if (array_key_exists('performance', $originalReports) === true) {
×
197
                $newReports['performance'] = $originalReports['performance'];
×
198
            }
199

200
            $this->config->reports = $newReports;
×
201

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

207
            $this->run();
×
208
            $this->reporter->printReports();
×
209

NEW
210
            if ($this->config->quiet === false) {
×
NEW
211
                StatusWriter::write('');
×
NEW
212
                Timing::printRunTime();
×
213
            }
214
        } catch (DeepExitException $e) {
×
215
            echo $e->getMessage();
×
216
            return $e->getCode();
×
217
        }//end try
218

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

230
        if ($this->reporter->totalFixable === 0) {
×
231
            // PHPCBF fixed all fixable errors.
232
            return 1;
×
233
        }
234

235
        // PHPCBF fixed some fixable errors, but others failed to fix.
236
        return 2;
×
237

238
    }//end runPHPCBF()
239

240

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

253
        // Disable the PCRE JIT as this caused issues with parallel running.
254
        ini_set('pcre.jit', false);
×
255

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

270
        // Saves passing the Config object into other objects that only need
271
        // the verbosity flag for debug output.
272
        if (defined('PHP_CODESNIFFER_VERBOSITY') === false) {
×
273
            define('PHP_CODESNIFFER_VERBOSITY', $this->config->verbosity);
×
274
        }
275

276
        // Create this class so it is autoloaded and sets up a bunch
277
        // of PHP_CodeSniffer-specific token type constants.
278
        new Tokens();
×
279

280
        // Allow autoloading of custom files inside installed standards.
281
        $installedStandards = Standards::getInstalledStandardDetails();
×
282
        foreach ($installedStandards as $details) {
×
283
            Autoload::addSearchPath($details['path'], $details['namespace']);
×
284
        }
285

286
        // The ruleset contains all the information about how the files
287
        // should be checked and/or fixed.
288
        try {
289
            $this->ruleset = new Ruleset($this->config);
×
290

291
            if ($this->ruleset->hasSniffDeprecations() === true) {
×
292
                $this->ruleset->showSniffDeprecations();
×
293
            }
294
        } catch (RuntimeException $e) {
×
295
            $error  = rtrim($e->getMessage(), "\r\n").PHP_EOL.PHP_EOL;
×
296
            $error .= $this->config->printShortUsage(true);
×
297
            throw new DeepExitException($error, 3);
×
298
        }
299

300
    }//end init()
301

302

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

315
        // Include bootstrap files.
316
        foreach ($this->config->bootstrap as $bootstrap) {
×
317
            include $bootstrap;
×
318
        }
319

320
        if ($this->config->stdin === true) {
×
321
            $fileContents = $this->config->stdinContent;
×
322
            if ($fileContents === null) {
×
323
                $handle = fopen('php://stdin', 'r');
×
324
                stream_set_blocking($handle, true);
×
325
                $fileContents = stream_get_contents($handle);
×
326
                fclose($handle);
×
327
            }
328

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

339
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
340
                StatusWriter::write('Creating file list... ', 0, 0);
×
341
            }
342

343
            $todo = new FileList($this->config, $this->ruleset);
×
344

345
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
346
                $numFiles = count($todo);
×
347
                StatusWriter::write("DONE ($numFiles files in queue)");
×
348
            }
349

350
            if ($this->config->cache === true) {
×
351
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
352
                    StatusWriter::write('Loading cache... ', 0, 0);
×
353
                }
354

355
                Cache::load($this->ruleset, $this->config);
×
356

357
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
358
                    $size = Cache::getSize();
×
359
                    StatusWriter::write("DONE ($size files in cache)");
×
360
                }
361
            }
362
        }//end if
363

364
        // Turn all sniff errors into exceptions.
365
        set_error_handler([$this, 'handleErrors']);
×
366

367
        // If verbosity is too high, turn off parallelism so the
368
        // debug output is clean.
369
        if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
370
            $this->config->parallel = 1;
×
371
        }
372

373
        // If the PCNTL extension isn't installed, we can't fork.
374
        if (function_exists('pcntl_fork') === false) {
×
375
            $this->config->parallel = 1;
×
376
        }
377

378
        $lastDir  = '';
×
379
        $numFiles = count($todo);
×
380

381
        if ($this->config->parallel === 1) {
×
382
            // Running normally.
383
            $numProcessed = 0;
×
384
            foreach ($todo as $path => $file) {
×
385
                if ($file->ignored === false) {
×
386
                    $currDir = dirname($path);
×
387
                    if ($lastDir !== $currDir) {
×
388
                        if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
389
                            StatusWriter::write('Changing into directory '.Common::stripBasepath($currDir, $this->config->basepath));
×
390
                        }
391

392
                        $lastDir = $currDir;
×
393
                    }
394

395
                    $this->processFile($file);
×
396
                } else if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
397
                    StatusWriter::write('Skipping '.basename($file->path));
×
398
                }
399

400
                $numProcessed++;
×
401
                $this->printProgress($file, $numFiles, $numProcessed);
×
402
            }
403
        } else {
404
            // Batching and forking.
405
            $childProcs  = [];
×
406
            $numPerBatch = ceil($numFiles / $this->config->parallel);
×
407

408
            for ($batch = 0; $batch < $this->config->parallel; $batch++) {
×
409
                $startAt = ($batch * $numPerBatch);
×
410
                if ($startAt >= $numFiles) {
×
411
                    break;
×
412
                }
413

414
                $endAt = ($startAt + $numPerBatch);
×
415
                if ($endAt > $numFiles) {
×
416
                    $endAt = $numFiles;
×
417
                }
418

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

432
                    // Reset the reporter to make sure only figures from this
433
                    // file batch are recorded.
434
                    $this->reporter->totalFiles    = 0;
×
435
                    $this->reporter->totalErrors   = 0;
×
436
                    $this->reporter->totalWarnings = 0;
×
437
                    $this->reporter->totalFixable  = 0;
×
438
                    $this->reporter->totalFixed    = 0;
×
439

440
                    // Process the files.
441
                    $pathsProcessed = [];
×
442
                    ob_start();
×
443
                    for ($i = $startAt; $i < $endAt; $i++) {
×
444
                        $path = $todo->key();
×
445
                        $file = $todo->current();
×
446

447
                        if ($file->ignored === true) {
×
448
                            $todo->next();
×
449
                            continue;
×
450
                        }
451

452
                        $currDir = dirname($path);
×
453
                        if ($lastDir !== $currDir) {
×
454
                            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
455
                                StatusWriter::write('Changing into directory '.Common::stripBasepath($currDir, $this->config->basepath));
×
456
                            }
457

458
                            $lastDir = $currDir;
×
459
                        }
460

461
                        $this->processFile($file);
×
462

463
                        $pathsProcessed[] = $path;
×
464
                        $todo->next();
×
465
                    }//end for
466

467
                    $debugOutput = ob_get_contents();
×
468
                    ob_end_clean();
×
469

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

480
                    $output  = '<'.'?php'."\n".' $childOutput = ';
×
481
                    $output .= var_export($childOutput, true);
×
482
                    $output .= ";\n\$debugOutput = ";
×
483
                    $output .= var_export($debugOutput, true);
×
484

485
                    if ($this->config->cache === true) {
×
486
                        $childCache = [];
×
487
                        foreach ($pathsProcessed as $path) {
×
488
                            $childCache[$path] = Cache::get($path);
×
489
                        }
490

491
                        $output .= ";\n\$childCache = ";
×
492
                        $output .= var_export($childCache, true);
×
493
                    }
494

495
                    $output .= ";\n?".'>';
×
496
                    file_put_contents($childOutFilename, $output);
×
497
                    exit();
×
498
                }//end if
499
            }//end for
500

501
            $success = $this->processChildProcs($childProcs);
×
502
            if ($success === false) {
×
503
                throw new RuntimeException('One or more child processes failed to run');
×
504
            }
505
        }//end if
506

507
        restore_error_handler();
×
508

509
        if (PHP_CODESNIFFER_VERBOSITY === 0
×
510
            && $this->config->interactive === false
×
511
            && $this->config->showProgress === true
×
512
        ) {
513
            StatusWriter::writeNewline(2);
×
514
        }
515

516
        if ($this->config->cache === true) {
×
517
            Cache::save();
×
518
        }
519

520
        $ignoreWarnings = Config::getConfigData('ignore_warnings_on_exit');
×
521
        $ignoreErrors   = Config::getConfigData('ignore_errors_on_exit');
×
522

523
        $return = ($this->reporter->totalErrors + $this->reporter->totalWarnings);
×
524
        if ($ignoreErrors !== null) {
×
525
            $ignoreErrors = (bool) $ignoreErrors;
×
526
            if ($ignoreErrors === true) {
×
527
                $return -= $this->reporter->totalErrors;
×
528
            }
529
        }
530

531
        if ($ignoreWarnings !== null) {
×
532
            $ignoreWarnings = (bool) $ignoreWarnings;
×
533
            if ($ignoreWarnings === true) {
×
534
                $return -= $this->reporter->totalWarnings;
×
535
            }
536
        }
537

538
        return $return;
×
539

540
    }//end run()
541

542

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

565
        throw new RuntimeException("$message in $file on line $line");
×
566

567
    }//end handleErrors()
568

569

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

587
            StatusWriter::write('Processing '.basename($file->path).' ', 0, $newlines);
×
588
        }
589

590
        try {
591
            $file->process();
×
592

593
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
594
                $timeTaken = ((microtime(true) - $startTime) * 1000);
×
595
                if ($timeTaken < 1000) {
×
596
                    $timeTaken = round($timeTaken);
×
597
                    StatusWriter::write("DONE in {$timeTaken}ms", 0, 0);
×
598
                } else {
599
                    $timeTaken = round(($timeTaken / 1000), 2);
×
600
                    StatusWriter::write("DONE in $timeTaken secs", 0, 0);
×
601
                }
602

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

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

623
                if (empty($sniffStack) === false) {
×
624
                    $nextStack = $step;
×
625
                    break;
×
626
                }
627

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

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

646
                if ($sniffCode === '') {
×
647
                    $sniffCode = substr(strrchr(str_replace('\\', '/', $sniffStack['file']), '/'), 1);
×
648
                }
649

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

653
            $file->addErrorOnLine($error, 1, 'Internal.Exception');
×
654
        }//end try
655

656
        $this->reporter->cacheFileReport($file);
×
657

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

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

673
                $this->reporter->printReport('full');
×
674

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

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

697
        // Clean up the file to save (a lot of) memory.
698
        $file->cleanUp();
×
699

700
    }//end processFile()
701

702

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

718
        $success = true;
×
719

720
        while (count($childProcs) > 0) {
×
721
            $pid = pcntl_waitpid(0, $status);
×
722
            if ($pid <= 0) {
×
723
                continue;
×
724
            }
725

726
            $childProcessStatus = pcntl_wexitstatus($status);
×
727
            if ($childProcessStatus !== 0) {
×
728
                $success = false;
×
729
            }
730

731
            $out = $childProcs[$pid];
×
732
            unset($childProcs[$pid]);
×
733
            if (file_exists($out) === false) {
×
734
                continue;
×
735
            }
736

737
            include $out;
×
738
            unlink($out);
×
739

740
            $numProcessed++;
×
741

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

751
            $this->reporter->totalFiles    += $childOutput['totalFiles'];
×
752
            $this->reporter->totalErrors   += $childOutput['totalErrors'];
×
753
            $this->reporter->totalWarnings += $childOutput['totalWarnings'];
×
754
            $this->reporter->totalFixable  += $childOutput['totalFixable'];
×
755
            $this->reporter->totalFixed    += $childOutput['totalFixed'];
×
756

757
            if (isset($debugOutput) === true) {
×
758
                echo $debugOutput;
×
759
            }
760

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

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

778
        return $success;
×
779

780
    }//end processChildProcs()
781

782

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

801
        $showColors  = $this->config->colors;
60✔
802
        $colorOpen   = '';
60✔
803
        $progressDot = '.';
60✔
804
        $colorClose  = '';
60✔
805

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

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

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

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

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

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

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

862
                        $colorClose = "\033[0m";
6✔
863
                    }
864
                }//end if
865
            }//end if
866
        }//end if
867

868
        StatusWriter::write($colorOpen.$progressDot.$colorClose, 0, 0);
60✔
869

870
        $numPerLine = 60;
60✔
871
        if ($numProcessed !== $numFiles && ($numProcessed % $numPerLine) !== 0) {
60✔
872
            return;
60✔
873
        }
874

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

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

886
    }//end printProgress()
6✔
887

888

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

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

924
    }//end registerOutOfMemoryShutdownMessage()
925

926

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