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

PHPCSStandards / PHP_CodeSniffer / 25057074115

28 Apr 2026 01:55PM UTC coverage: 78.951% (-0.02%) from 78.969%
25057074115

Pull #1421

github

web-flow
Merge 687fea77c into c3eb74d77
Pull Request #1421: Runner: distribute files round-robin by size in parallel mode

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

1 existing line in 1 file now uncovered.

19875 of 25174 relevant lines covered (78.95%)

98.85 hits per line

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

21.01
/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-2023 Squiz Pty Ltd (ABN 77 084 670 600)
10
 * @copyright 2023 PHPCSStandards and contributors
11
 * @license   https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/HEAD/licence.txt BSD Licence
12
 */
13

14
namespace PHP_CodeSniffer;
15

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

32
class Runner
33
{
34

35
    /**
36
     * The config data for the run.
37
     *
38
     * @var \PHP_CodeSniffer\Config
39
     */
40
    public $config = null;
41

42
    /**
43
     * The ruleset used for the run.
44
     *
45
     * @var \PHP_CodeSniffer\Ruleset
46
     */
47
    public $ruleset = null;
48

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

56

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

66
        try {
67
            Timing::startTiming();
8✔
68

69
            if (defined('PHP_CODESNIFFER_CBF') === false) {
8✔
70
                define('PHP_CODESNIFFER_CBF', false);
×
71
            }
72

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

78
            // Init the run and load the rulesets to set additional config vars.
79
            $this->init();
8✔
80

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

91
                return 0;
3✔
92
            }
93

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

105
                return 0;
5✔
106
            }
107

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

117
            // Disable caching if we are processing STDIN as we can't be 100%
118
            // sure where the file came from or if it will change in the future.
119
            // Also disable parallel processing because STDIN is a single file
120
            // held in memory and the workers can't see it across the fork.
121
            if ($this->config->stdin === true) {
×
NEW
122
                $this->config->cache    = false;
×
NEW
123
                $this->config->parallel = 1;
×
124
            }
125

126
            $this->run();
×
127

128
            // Print all the reports for this run.
129
            $this->reporter->printReports();
×
130

131
            if ($this->config->quiet === false) {
×
132
                Timing::printRunTime();
×
133
            }
134
        } catch (DeepExitException $e) {
×
135
            $exitCode = $e->getCode();
×
136
            $message  = $e->getMessage();
×
137
            if ($message !== '') {
×
138
                if ($exitCode === 0) {
×
139
                    echo $e->getMessage();
×
140
                } else {
141
                    StatusWriter::write($e->getMessage(), 0, 0);
×
142
                }
143
            }
144

145
            return $exitCode;
×
146
        }
147

148
        return ExitCode::calculate($this->reporter);
×
149
    }
150

151

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

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

165
        try {
166
            Timing::startTiming();
×
167

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

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

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

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

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

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

205
            $this->config->reports = $newReports;
×
206

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

212
            $this->run();
×
213
            $this->reporter->printReports();
×
214

215
            if ($this->config->quiet === false) {
×
216
                StatusWriter::writeNewline();
×
217
                Timing::printRunTime();
×
218
            }
219
        } catch (DeepExitException $e) {
×
220
            $exitCode = $e->getCode();
×
221
            $message  = $e->getMessage();
×
222
            if ($message !== '') {
×
223
                if ($exitCode === 0) {
×
224
                    echo $e->getMessage();
×
225
                } else {
226
                    StatusWriter::write($e->getMessage(), 0, 0);
×
227
                }
228
            }
229

230
            return $exitCode;
×
231
        }
232

233
        return ExitCode::calculate($this->reporter);
×
234
    }
235

236

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

249
        // Disable the PCRE JIT as this caused issues with parallel running.
250
        ini_set('pcre.jit', false);
×
251

252
        // Check that the standards are valid.
253
        foreach ($this->config->standards as $standard) {
×
254
            if (Standards::isInstalledStandard($standard) === false) {
×
255
                // They didn't select a valid coding standard, so help them
256
                // out by letting them know which standards are installed.
257
                $error  = 'ERROR: the "' . $standard . '" coding standard is not installed.' . PHP_EOL . PHP_EOL;
×
258
                $error .= Standards::prepareInstalledStandardsForDisplay() . PHP_EOL;
×
259
                throw new DeepExitException($error, ExitCode::PROCESS_ERROR);
×
260
            }
261
        }
262

263
        // Saves passing the Config object into other objects that only need
264
        // the verbosity flag for debug output.
265
        if (defined('PHP_CODESNIFFER_VERBOSITY') === false) {
×
266
            define('PHP_CODESNIFFER_VERBOSITY', $this->config->verbosity);
×
267
        }
268

269
        // Create this class so it is autoloaded and sets up a bunch
270
        // of PHP_CodeSniffer-specific token type constants.
271
        new Tokens();
×
272

273
        // Allow autoloading of custom files inside installed standards.
274
        $installedStandards = Standards::getInstalledStandardDetails();
×
275
        foreach ($installedStandards as $details) {
×
276
            Autoload::addSearchPath($details['path'], $details['namespace']);
×
277
        }
278

279
        // The ruleset contains all the information about how the files
280
        // should be checked and/or fixed.
281
        try {
282
            $this->ruleset = new Ruleset($this->config);
×
283

284
            if ($this->ruleset->hasSniffDeprecations() === true) {
×
285
                $this->ruleset->showSniffDeprecations();
×
286
            }
287
        } catch (RuntimeException $e) {
×
288
            $error  = rtrim($e->getMessage(), "\r\n") . PHP_EOL . PHP_EOL;
×
289
            $error .= $this->config->printShortUsage(true);
×
290
            throw new DeepExitException($error, ExitCode::PROCESS_ERROR);
×
291
        }
292
    }
293

294

295
    /**
296
     * Performs the run.
297
     *
298
     * @return void
299
     *
300
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
301
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException
302
     */
303
    private function run()
12✔
304
    {
305
        // The class that manages all reporters for the run.
306
        $this->reporter = new Reporter($this->config);
12✔
307

308
        // Include bootstrap files.
309
        foreach ($this->config->bootstrap as $bootstrap) {
12✔
310
            include $bootstrap;
×
311
        }
312

313
        if ($this->config->stdin === true) {
12✔
314
            $fileContents = $this->config->stdinContent;
×
315
            if ($fileContents === null) {
×
316
                $handle = fopen('php://stdin', 'r');
×
317
                stream_set_blocking($handle, true);
×
318
                $fileContents = stream_get_contents($handle);
×
319
                fclose($handle);
×
320
            }
321

322
            $todo  = new FileList($this->config, $this->ruleset);
×
323
            $dummy = new DummyFile($fileContents, $this->ruleset, $this->config);
×
324
            $todo->addFile($dummy->path, $dummy);
×
325
        } else {
326
            if (empty($this->config->files) === true) {
12✔
327
                $error  = 'ERROR: You must supply at least one file or directory to process.' . PHP_EOL . PHP_EOL;
×
328
                $error .= $this->config->printShortUsage(true);
×
329
                throw new DeepExitException($error, ExitCode::PROCESS_ERROR);
×
330
            }
331

332
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
12✔
333
                StatusWriter::write('Creating file list... ', 0, 0);
×
334
            }
335

336
            $todo = new FileList($this->config, $this->ruleset);
12✔
337

338
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
12✔
339
                $numFiles = count($todo);
×
340
                StatusWriter::write("DONE ($numFiles files in queue)");
×
341
            }
342

343
            if ($this->config->cache === true) {
12✔
344
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
345
                    StatusWriter::write('Loading cache... ', 0, 0);
×
346
                }
347

348
                Cache::load($this->ruleset, $this->config);
×
349

350
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
351
                    $size = Cache::getSize();
×
352
                    StatusWriter::write("DONE ($size files in cache)");
×
353
                }
354
            }
355
        }
356

357
        $numFiles = count($todo);
12✔
358
        if ($numFiles === 0) {
12✔
359
            $error  = 'ERROR: No files were checked.' . PHP_EOL;
12✔
360
            $error .= 'All specified files were excluded or did not match filtering rules.' . PHP_EOL . PHP_EOL;
12✔
361
            throw new DeepExitException($error, ExitCode::PROCESS_ERROR);
12✔
362
        }
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

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

391
                        $lastDir = $currDir;
×
392
                    }
393

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

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

406
            // Distribute files round-robin in size order so each batch
407
            // ends up with a similar total workload.
NEW
408
            $sortedPaths = [];
×
NEW
409
            $todo->rewind();
×
NEW
410
            while ($todo->valid() === true) {
×
NEW
411
                $sortedPaths[] = $todo->key();
×
NEW
412
                $todo->next();
×
413
            }
414

NEW
415
            $sizes = [];
×
NEW
416
            foreach ($sortedPaths as $path) {
×
NEW
417
                $size = @filesize($path);
×
NEW
418
                if ($size === false) {
×
NEW
419
                    $size = 0;
×
420
                }
421

NEW
422
                $sizes[$path] = $size;
×
423
            }
424

NEW
425
            usort(
×
NEW
426
                $sortedPaths,
×
427
                static function ($a, $b) use ($sizes) {
NEW
428
                    return ($sizes[$b] - $sizes[$a]);
×
UNCOV
429
                }
×
430
            );
431

NEW
432
            for ($batch = 0; $batch < $this->config->parallel; $batch++) {
×
NEW
433
                if ($batch >= $numFiles) {
×
NEW
434
                    break;
×
435
                }
436

437
                $childOutFilename = tempnam(sys_get_temp_dir(), 'phpcs-child');
×
438
                $pid = pcntl_fork();
×
439
                if ($pid === -1) {
×
440
                    throw new RuntimeException('Failed to create child process');
×
441
                } elseif ($pid !== 0) {
×
442
                    $childProcs[$pid] = $childOutFilename;
×
443
                } else {
444
                    // Reset the reporter to make sure only figures from this
445
                    // file batch are recorded.
446
                    $this->reporter->totalFiles           = 0;
×
447
                    $this->reporter->totalErrors          = 0;
×
448
                    $this->reporter->totalWarnings        = 0;
×
449
                    $this->reporter->totalFixableErrors   = 0;
×
450
                    $this->reporter->totalFixableWarnings = 0;
×
451
                    $this->reporter->totalFixedErrors     = 0;
×
452
                    $this->reporter->totalFixedWarnings   = 0;
×
453

454
                    // Process the files.
455
                    $pathsProcessed = [];
×
456
                    ob_start();
×
NEW
457
                    for ($i = $batch; $i < $numFiles; $i += $this->config->parallel) {
×
NEW
458
                        $path = $sortedPaths[$i];
×
NEW
459
                        $file = new LocalFile($path, $this->ruleset, $this->config);
×
460

461
                        if ($file->ignored === true) {
×
462
                            continue;
×
463
                        }
464

465
                        $currDir = dirname($path);
×
466
                        if ($lastDir !== $currDir) {
×
467
                            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
468
                                StatusWriter::write('Changing into directory ' . Common::stripBasepath($currDir, $this->config->basepath));
×
469
                            }
470

471
                            $lastDir = $currDir;
×
472
                        }
473

474
                        $this->processFile($file);
×
475

476
                        $pathsProcessed[] = $path;
×
477
                    }
478

479
                    $debugOutput = ob_get_contents();
×
480
                    ob_end_clean();
×
481

482
                    // Write information about the run to the filesystem
483
                    // so it can be picked up by the main process.
484
                    $childOutput = [
485
                        'totalFiles'           => $this->reporter->totalFiles,
×
486
                        'totalErrors'          => $this->reporter->totalErrors,
×
487
                        'totalWarnings'        => $this->reporter->totalWarnings,
×
488
                        'totalFixableErrors'   => $this->reporter->totalFixableErrors,
×
489
                        'totalFixableWarnings' => $this->reporter->totalFixableWarnings,
×
490
                        'totalFixedErrors'     => $this->reporter->totalFixedErrors,
×
491
                        'totalFixedWarnings'   => $this->reporter->totalFixedWarnings,
×
492
                    ];
493

494
                    $output  = '<' . '?php' . "\n" . ' $childOutput = ';
×
495
                    $output .= var_export($childOutput, true);
×
496
                    $output .= ";\n\$debugOutput = ";
×
497
                    $output .= var_export($debugOutput, true);
×
498

499
                    if ($this->config->cache === true) {
×
500
                        $childCache = [];
×
501
                        foreach ($pathsProcessed as $path) {
×
502
                            $childCache[$path] = Cache::get($path);
×
503
                        }
504

505
                        $output .= ";\n\$childCache = ";
×
506
                        $output .= var_export($childCache, true);
×
507
                    }
508

509
                    $output .= ";\n?" . '>';
×
510
                    file_put_contents($childOutFilename, $output);
×
511
                    exit();
×
512
                }
513
            }
514

515
            $success = $this->processChildProcs($childProcs);
×
516
            if ($success === false) {
×
517
                throw new RuntimeException('One or more child processes failed to run');
×
518
            }
519
        }
520

521
        restore_error_handler();
×
522

523
        if (PHP_CODESNIFFER_VERBOSITY === 0
×
524
            && $this->config->interactive === false
×
525
            && $this->config->showProgress === true
×
526
        ) {
527
            StatusWriter::writeNewline(2);
×
528
        }
529

530
        if ($this->config->cache === true) {
×
531
            Cache::save();
×
532
        }
533
    }
534

535

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

558
        throw new RuntimeException("$message in $file on line $line");
×
559
    }
560

561

562
    /**
563
     * Processes a single file, including checking and fixing.
564
     *
565
     * @param \PHP_CodeSniffer\Files\File $file The file to be processed.
566
     *
567
     * @return void
568
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
569
     */
570
    public function processFile(File $file)
×
571
    {
572
        if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
573
            $startTime = microtime(true);
×
574
            $newlines  = 0;
×
575
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
576
                $newlines = 1;
×
577
            }
578

579
            StatusWriter::write('Processing ' . basename($file->path) . ' ', 0, $newlines);
×
580
        }
581

582
        try {
583
            $file->process();
×
584

585
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
586
                StatusWriter::write('DONE in ' . Timing::getHumanReadableDuration(Timing::getDurationSince($startTime)), 0, 0);
×
587

588
                if (PHP_CODESNIFFER_CBF === true) {
×
589
                    $errors   = $file->getFixableErrorCount();
×
590
                    $warnings = $file->getFixableWarningCount();
×
591
                    StatusWriter::write(" ($errors fixable errors, $warnings fixable warnings)");
×
592
                } else {
593
                    $errors   = $file->getErrorCount();
×
594
                    $warnings = $file->getWarningCount();
×
595
                    StatusWriter::write(" ($errors errors, $warnings warnings)");
×
596
                }
597
            }
598
        } catch (Exception $e) {
×
599
            $error = 'An error occurred during processing; checking has been aborted. The error message was: ' . $e->getMessage();
×
600

601
            // Determine which sniff caused the error.
602
            $sniffStack = null;
×
603
            $nextStack  = null;
×
604
            foreach ($e->getTrace() as $step) {
×
605
                if (isset($step['file']) === false) {
×
606
                    continue;
×
607
                }
608

609
                if (empty($sniffStack) === false) {
×
610
                    $nextStack = $step;
×
611
                    break;
×
612
                }
613

614
                if (substr($step['file'], -9) === 'Sniff.php') {
×
615
                    $sniffStack = $step;
×
616
                    continue;
×
617
                }
618
            }
619

620
            if (empty($sniffStack) === false) {
×
621
                $sniffCode = '';
×
622
                try {
623
                    if (empty($nextStack) === false
×
624
                        && isset($nextStack['class']) === true
×
625
                    ) {
626
                        $sniffCode = 'the ' . Common::getSniffCode($nextStack['class']) . ' sniff';
×
627
                    }
628
                } catch (InvalidArgumentException $e) {
×
629
                    // Sniff code could not be determined. This may be an abstract sniff class.
630
                }
631

632
                if ($sniffCode === '') {
×
633
                    $sniffCode = substr(strrchr(str_replace('\\', '/', $sniffStack['file']), '/'), 1);
×
634
                }
635

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

639
            $file->addErrorOnLine($error, 1, 'Internal.Exception');
×
640
        }
641

642
        $this->reporter->cacheFileReport($file);
×
643

644
        if ($this->config->interactive === true) {
×
645
            /*
646
                Running interactively.
647
                Print the error report for the current file and then wait for user input.
648
            */
649

650
            // Get current violations and then clear the list to make sure
651
            // we only print violations for a single file each time.
652
            $numErrors = null;
×
653
            while ($numErrors !== 0) {
×
654
                $numErrors = ($file->getErrorCount() + $file->getWarningCount());
×
655
                if ($numErrors === 0) {
×
656
                    continue;
×
657
                }
658

659
                $this->reporter->printReport('full');
×
660

661
                echo '<ENTER> to recheck, [s] to skip or [q] to quit : ';
×
662
                $input = fgets(STDIN);
×
663
                $input = trim($input);
×
664

665
                switch ($input) {
666
                    case 's':
×
667
                        break(2);
×
668
                    case 'q':
×
669
                        // User request to "quit": exit code should be 0.
670
                        throw new DeepExitException('', ExitCode::OKAY);
×
671
                    default:
672
                        // Repopulate the sniffs because some of them save their state
673
                        // and only clear it when the file changes, but we are rechecking
674
                        // the same file.
675
                        $file->ruleset->populateTokenListeners();
×
676
                        $file->reloadContent();
×
677
                        $file->process();
×
678
                        $this->reporter->cacheFileReport($file);
×
679
                        break;
×
680
                }
681
            }
682
        }
683

684
        // Clean up the file to save (a lot of) memory.
685
        $file->cleanUp();
×
686
    }
687

688

689
    /**
690
     * Waits for child processes to complete and cleans up after them.
691
     *
692
     * The reporting information returned by each child process is merged
693
     * into the main reporter class.
694
     *
695
     * @param array<int, string> $childProcs An array of child processes to wait for.
696
     *
697
     * @return bool
698
     */
699
    private function processChildProcs(array $childProcs)
×
700
    {
701
        $numProcessed = 0;
×
702
        $totalBatches = count($childProcs);
×
703

704
        $success = true;
×
705

706
        while (count($childProcs) > 0) {
×
707
            $pid = pcntl_waitpid(0, $status);
×
708
            if ($pid <= 0 || isset($childProcs[$pid]) === false) {
×
709
                // No child or a child with an unmanaged PID was returned.
710
                continue;
×
711
            }
712

713
            $childProcessStatus = pcntl_wexitstatus($status);
×
714
            if ($childProcessStatus !== 0) {
×
715
                $success = false;
×
716
            }
717

718
            $out = $childProcs[$pid];
×
719
            unset($childProcs[$pid]);
×
720
            if (file_exists($out) === false) {
×
721
                continue;
×
722
            }
723

724
            include $out;
×
725
            unlink($out);
×
726

727
            $numProcessed++;
×
728

729
            if (isset($childOutput) === false) {
×
730
                // The child process died, so the run has failed.
731
                $file = new DummyFile('', $this->ruleset, $this->config);
×
732
                $file->setErrorCounts(1, 0, 0, 0, 0, 0);
×
733
                $this->printProgress($file, $totalBatches, $numProcessed);
×
734
                $success = false;
×
735
                continue;
×
736
            }
737

738
            $this->reporter->totalFiles           += $childOutput['totalFiles'];
×
739
            $this->reporter->totalErrors          += $childOutput['totalErrors'];
×
740
            $this->reporter->totalWarnings        += $childOutput['totalWarnings'];
×
741
            $this->reporter->totalFixableErrors   += $childOutput['totalFixableErrors'];
×
742
            $this->reporter->totalFixableWarnings += $childOutput['totalFixableWarnings'];
×
743
            $this->reporter->totalFixedErrors     += $childOutput['totalFixedErrors'];
×
744
            $this->reporter->totalFixedWarnings   += $childOutput['totalFixedWarnings'];
×
745

746
            if (isset($debugOutput) === true) {
×
747
                echo $debugOutput;
×
748
            }
749

750
            if (isset($childCache) === true) {
×
751
                foreach ($childCache as $path => $cache) {
×
752
                    Cache::set($path, $cache);
×
753
                }
754
            }
755

756
            // Fake a processed file so we can print progress output for the batch.
757
            $file = new DummyFile('', $this->ruleset, $this->config);
×
758
            $file->setErrorCounts(
×
759
                $childOutput['totalErrors'],
×
760
                $childOutput['totalWarnings'],
×
761
                $childOutput['totalFixableErrors'],
×
762
                $childOutput['totalFixableWarnings'],
×
763
                $childOutput['totalFixedErrors'],
×
764
                $childOutput['totalFixedWarnings']
×
765
            );
766
            $this->printProgress($file, $totalBatches, $numProcessed);
×
767
        }
768

769
        return $success;
×
770
    }
771

772

773
    /**
774
     * Print progress information for a single processed file.
775
     *
776
     * @param \PHP_CodeSniffer\Files\File $file         The file that was processed.
777
     * @param int                         $numFiles     The total number of files to process.
778
     * @param int                         $numProcessed The number of files that have been processed,
779
     *                                                  including this one.
780
     *
781
     * @return void
782
     */
783
    public function printProgress(File $file, int $numFiles, int $numProcessed)
63✔
784
    {
785
        if (PHP_CODESNIFFER_VERBOSITY > 0
63✔
786
            || $this->config->showProgress === false
63✔
787
        ) {
788
            return;
3✔
789
        }
790

791
        $showColors  = $this->config->colors;
60✔
792
        $colorOpen   = '';
60✔
793
        $progressDot = '.';
60✔
794
        $colorClose  = '';
60✔
795

796
        // Show progress information.
797
        if ($file->ignored === true) {
60✔
798
            $progressDot = 'S';
3✔
799
        } else {
800
            $errors   = $file->getErrorCount();
60✔
801
            $warnings = $file->getWarningCount();
60✔
802
            $fixable  = $file->getFixableCount();
60✔
803
            $fixed    = ($file->getFixedErrorCount() + $file->getFixedWarningCount());
60✔
804

805
            if (PHP_CODESNIFFER_CBF === true) {
60✔
806
                // Files with fixed errors or warnings are F (green).
807
                // Files with unfixable errors or warnings are E (red).
808
                // Files with no errors or warnings are . (black).
809
                if ($fixable > 0) {
18✔
810
                    $progressDot = 'E';
6✔
811

812
                    if ($showColors === true) {
6✔
813
                        $colorOpen  = "\033[31m";
3✔
814
                        $colorClose = "\033[0m";
4✔
815
                    }
816
                } elseif ($fixed > 0) {
12✔
817
                    $progressDot = 'F';
6✔
818

819
                    if ($showColors === true) {
6✔
820
                        $colorOpen  = "\033[32m";
3✔
821
                        $colorClose = "\033[0m";
8✔
822
                    }
823
                }
824
            } else {
825
                // Files with errors are E (red).
826
                // Files with fixable errors are E (green).
827
                // Files with warnings are W (yellow).
828
                // Files with fixable warnings are W (green).
829
                // Files with no errors or warnings are . (black).
830
                if ($errors > 0) {
42✔
831
                    $progressDot = 'E';
9✔
832

833
                    if ($showColors === true) {
9✔
834
                        if ($fixable > 0) {
6✔
835
                            $colorOpen = "\033[32m";
3✔
836
                        } else {
837
                            $colorOpen = "\033[31m";
3✔
838
                        }
839

840
                        $colorClose = "\033[0m";
7✔
841
                    }
842
                } elseif ($warnings > 0) {
33✔
843
                    $progressDot = 'W';
9✔
844

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

852
                        $colorClose = "\033[0m";
6✔
853
                    }
854
                }
855
            }
856
        }
857

858
        StatusWriter::write($colorOpen . $progressDot . $colorClose, 0, 0);
60✔
859

860
        $numPerLine = 60;
60✔
861
        if ($numProcessed !== $numFiles && ($numProcessed % $numPerLine) !== 0) {
60✔
862
            return;
60✔
863
        }
864

865
        $percent = round(($numProcessed / $numFiles) * 100);
18✔
866
        $padding = (strlen($numFiles) - strlen($numProcessed));
18✔
867
        if ($numProcessed === $numFiles
18✔
868
            && $numFiles > $numPerLine
18✔
869
            && ($numProcessed % $numPerLine) !== 0
18✔
870
        ) {
871
            $padding += ($numPerLine - ($numFiles - (floor($numFiles / $numPerLine) * $numPerLine)));
9✔
872
        }
873

874
        StatusWriter::write(str_repeat(' ', $padding) . " $numProcessed / $numFiles ($percent%)");
18✔
875
    }
6✔
876

877

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

900
        register_shutdown_function(
×
901
            static function () use (
902
                $errorMsg,
×
903
                $memoryError,
×
904
                $errorArray
×
905
            ) {
906
                $errorArray = error_get_last();
×
907
                if (is_array($errorArray) === true && strpos($errorArray['message'], $memoryError) !== false) {
×
908
                    fwrite(STDERR, $errorMsg);
×
909
                }
910
            }
×
911
        );
912
    }
913
}
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