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

PHPCSStandards / PHP_CodeSniffer / 17663981080

12 Sep 2025 03:49AM UTC coverage: 78.786%. Remained the same
17663981080

push

github

web-flow
Merge pull request #1245 from PHPCSStandards/phpcs-4.x/feature/155-normalize-some-code-style-rules-7

CS: normalize code style rules [7]

677 of 1022 new or added lines in 17 files covered. (66.24%)

7 existing lines in 1 file now uncovered.

19732 of 25045 relevant lines covered (78.79%)

96.47 hits per line

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

21.32
/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\ExitCode;
25
use PHP_CodeSniffer\Util\Standards;
26
use PHP_CodeSniffer\Util\Timing;
27
use PHP_CodeSniffer\Util\Tokens;
28
use PHP_CodeSniffer\Util\Writers\StatusWriter;
29

30
class Runner
31
{
32

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

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

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

54

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

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

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

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

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

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

89
                return 0;
3✔
90
            }
91

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

103
                return 0;
5✔
104
            }
105

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

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

121
            $this->run();
×
122

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

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

140
            return $exitCode;
×
141
        }
142

143
        return ExitCode::calculate($this->reporter);
×
144
    }
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

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

225
            return $exitCode;
×
226
        }
227

228
        return ExitCode::calculate($this->reporter);
×
229
    }
230

231

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

244
        // Disable the PCRE JIT as this caused issues with parallel running.
245
        ini_set('pcre.jit', false);
×
246

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

258
        // Saves passing the Config object into other objects that only need
259
        // the verbosity flag for debug output.
260
        if (defined('PHP_CODESNIFFER_VERBOSITY') === false) {
×
261
            define('PHP_CODESNIFFER_VERBOSITY', $this->config->verbosity);
×
262
        }
263

264
        // Create this class so it is autoloaded and sets up a bunch
265
        // of PHP_CodeSniffer-specific token type constants.
266
        new Tokens();
×
267

268
        // Allow autoloading of custom files inside installed standards.
269
        $installedStandards = Standards::getInstalledStandardDetails();
×
270
        foreach ($installedStandards as $details) {
×
271
            Autoload::addSearchPath($details['path'], $details['namespace']);
×
272
        }
273

274
        // The ruleset contains all the information about how the files
275
        // should be checked and/or fixed.
276
        try {
277
            $this->ruleset = new Ruleset($this->config);
×
278

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

289

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

303
        // Include bootstrap files.
304
        foreach ($this->config->bootstrap as $bootstrap) {
12✔
305
            include $bootstrap;
×
306
        }
307

308
        if ($this->config->stdin === true) {
12✔
309
            $fileContents = $this->config->stdinContent;
×
310
            if ($fileContents === null) {
×
311
                $handle = fopen('php://stdin', 'r');
×
312
                stream_set_blocking($handle, true);
×
313
                $fileContents = stream_get_contents($handle);
×
314
                fclose($handle);
×
315
            }
316

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

327
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
12✔
328
                StatusWriter::write('Creating file list... ', 0, 0);
×
329
            }
330

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

333
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
12✔
334
                $numFiles = count($todo);
×
335
                StatusWriter::write("DONE ($numFiles files in queue)");
×
336
            }
337

338
            if ($this->config->cache === true) {
12✔
339
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
340
                    StatusWriter::write('Loading cache... ', 0, 0);
×
341
                }
342

343
                Cache::load($this->ruleset, $this->config);
×
344

345
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
346
                    $size = Cache::getSize();
×
347
                    StatusWriter::write("DONE ($size files in cache)");
×
348
                }
349
            }
350
        }
351

352
        $numFiles = count($todo);
12✔
353
        if ($numFiles === 0) {
12✔
354
            $error  = 'ERROR: No files were checked.' . PHP_EOL;
12✔
355
            $error .= 'All specified files were excluded or did not match filtering rules.' . PHP_EOL . PHP_EOL;
12✔
356
            throw new DeepExitException($error, ExitCode::PROCESS_ERROR);
12✔
357
        }
358

359
        // Turn all sniff errors into exceptions.
360
        set_error_handler([$this, 'handleErrors']);
×
361

362
        // If verbosity is too high, turn off parallelism so the
363
        // debug output is clean.
364
        if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
365
            $this->config->parallel = 1;
×
366
        }
367

368
        // If the PCNTL extension isn't installed, we can't fork.
369
        if (function_exists('pcntl_fork') === false) {
×
370
            $this->config->parallel = 1;
×
371
        }
372

373
        $lastDir = '';
×
374

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

386
                        $lastDir = $currDir;
×
387
                    }
388

389
                    $this->processFile($file);
×
390
                } elseif (PHP_CODESNIFFER_VERBOSITY > 0) {
×
391
                    StatusWriter::write('Skipping ' . basename($file->path));
×
392
                }
393

394
                $numProcessed++;
×
395
                $this->printProgress($file, $numFiles, $numProcessed);
×
396
            }
397
        } else {
398
            // Batching and forking.
399
            $childProcs  = [];
×
400
            $numPerBatch = ceil($numFiles / $this->config->parallel);
×
401

402
            for ($batch = 0; $batch < $this->config->parallel; $batch++) {
×
403
                $startAt = ($batch * $numPerBatch);
×
404
                if ($startAt >= $numFiles) {
×
405
                    break;
×
406
                }
407

408
                $endAt = ($startAt + $numPerBatch);
×
409
                if ($endAt > $numFiles) {
×
410
                    $endAt = $numFiles;
×
411
                }
412

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

426
                    // Reset the reporter to make sure only figures from this
427
                    // file batch are recorded.
428
                    $this->reporter->totalFiles           = 0;
×
429
                    $this->reporter->totalErrors          = 0;
×
430
                    $this->reporter->totalWarnings        = 0;
×
431
                    $this->reporter->totalFixableErrors   = 0;
×
432
                    $this->reporter->totalFixableWarnings = 0;
×
433
                    $this->reporter->totalFixedErrors     = 0;
×
434
                    $this->reporter->totalFixedWarnings   = 0;
×
435

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

443
                        if ($file->ignored === true) {
×
444
                            $todo->next();
×
445
                            continue;
×
446
                        }
447

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

454
                            $lastDir = $currDir;
×
455
                        }
456

457
                        $this->processFile($file);
×
458

459
                        $pathsProcessed[] = $path;
×
460
                        $todo->next();
×
461
                    }
462

463
                    $debugOutput = ob_get_contents();
×
464
                    ob_end_clean();
×
465

466
                    // Write information about the run to the filesystem
467
                    // so it can be picked up by the main process.
468
                    $childOutput = [
469
                        'totalFiles'           => $this->reporter->totalFiles,
×
470
                        'totalErrors'          => $this->reporter->totalErrors,
×
471
                        'totalWarnings'        => $this->reporter->totalWarnings,
×
472
                        'totalFixableErrors'   => $this->reporter->totalFixableErrors,
×
473
                        'totalFixableWarnings' => $this->reporter->totalFixableWarnings,
×
474
                        'totalFixedErrors'     => $this->reporter->totalFixedErrors,
×
475
                        'totalFixedWarnings'   => $this->reporter->totalFixedWarnings,
×
476
                    ];
477

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

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

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

493
                    $output .= ";\n?" . '>';
×
494
                    file_put_contents($childOutFilename, $output);
×
495
                    exit();
×
496
                }
497
            }
498

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

505
        restore_error_handler();
×
506

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

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

519

520
    /**
521
     * Converts all PHP errors into exceptions.
522
     *
523
     * This method forces a sniff to stop processing if it is not
524
     * able to handle a specific piece of code, instead of continuing
525
     * and potentially getting into a loop.
526
     *
527
     * @param int    $code    The level of error raised.
528
     * @param string $message The error message.
529
     * @param string $file    The path of the file that raised the error.
530
     * @param int    $line    The line number the error was raised at.
531
     *
532
     * @return bool
533
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException
534
     */
535
    public function handleErrors(int $code, string $message, string $file, int $line)
×
536
    {
537
        if ((error_reporting() & $code) === 0) {
×
538
            // This type of error is being muted.
539
            return true;
×
540
        }
541

542
        throw new RuntimeException("$message in $file on line $line");
×
543
    }
544

545

546
    /**
547
     * Processes a single file, including checking and fixing.
548
     *
549
     * @param \PHP_CodeSniffer\Files\File $file The file to be processed.
550
     *
551
     * @return void
552
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
553
     */
554
    public function processFile(File $file)
×
555
    {
556
        if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
557
            $startTime = microtime(true);
×
558
            $newlines  = 0;
×
559
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
560
                $newlines = 1;
×
561
            }
562

563
            StatusWriter::write('Processing ' . basename($file->path) . ' ', 0, $newlines);
×
564
        }
565

566
        try {
567
            $file->process();
×
568

569
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
570
                StatusWriter::write('DONE in ' . Timing::getHumanReadableDuration(Timing::getDurationSince($startTime)), 0, 0);
×
571

572
                if (PHP_CODESNIFFER_CBF === true) {
×
573
                    $errors   = $file->getFixableErrorCount();
×
574
                    $warnings = $file->getFixableWarningCount();
×
575
                    StatusWriter::write(" ($errors fixable errors, $warnings fixable warnings)");
×
576
                } else {
577
                    $errors   = $file->getErrorCount();
×
578
                    $warnings = $file->getWarningCount();
×
579
                    StatusWriter::write(" ($errors errors, $warnings warnings)");
×
580
                }
581
            }
582
        } catch (Exception $e) {
×
583
            $error = 'An error occurred during processing; checking has been aborted. The error message was: ' . $e->getMessage();
×
584

585
            // Determine which sniff caused the error.
586
            $sniffStack = null;
×
587
            $nextStack  = null;
×
588
            foreach ($e->getTrace() as $step) {
×
589
                if (isset($step['file']) === false) {
×
590
                    continue;
×
591
                }
592

593
                if (empty($sniffStack) === false) {
×
594
                    $nextStack = $step;
×
595
                    break;
×
596
                }
597

598
                if (substr($step['file'], -9) === 'Sniff.php') {
×
599
                    $sniffStack = $step;
×
600
                    continue;
×
601
                }
602
            }
603

604
            if (empty($sniffStack) === false) {
×
605
                $sniffCode = '';
×
606
                try {
607
                    if (empty($nextStack) === false
×
608
                        && isset($nextStack['class']) === true
×
609
                    ) {
610
                        $sniffCode = 'the ' . Common::getSniffCode($nextStack['class']) . ' sniff';
×
611
                    }
612
                } catch (InvalidArgumentException $e) {
×
613
                    // Sniff code could not be determined. This may be an abstract sniff class.
614
                }
615

616
                if ($sniffCode === '') {
×
617
                    $sniffCode = substr(strrchr(str_replace('\\', '/', $sniffStack['file']), '/'), 1);
×
618
                }
619

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

623
            $file->addErrorOnLine($error, 1, 'Internal.Exception');
×
624
        }
625

626
        $this->reporter->cacheFileReport($file);
×
627

628
        if ($this->config->interactive === true) {
×
629
            /*
630
                Running interactively.
631
                Print the error report for the current file and then wait for user input.
632
            */
633

634
            // Get current violations and then clear the list to make sure
635
            // we only print violations for a single file each time.
636
            $numErrors = null;
×
637
            while ($numErrors !== 0) {
×
638
                $numErrors = ($file->getErrorCount() + $file->getWarningCount());
×
639
                if ($numErrors === 0) {
×
640
                    continue;
×
641
                }
642

643
                $this->reporter->printReport('full');
×
644

645
                echo '<ENTER> to recheck, [s] to skip or [q] to quit : ';
×
646
                $input = fgets(STDIN);
×
647
                $input = trim($input);
×
648

649
                switch ($input) {
NEW
650
                    case 's':
×
NEW
651
                        break(2);
×
NEW
652
                    case 'q':
×
653
                        // User request to "quit": exit code should be 0.
NEW
654
                        throw new DeepExitException('', ExitCode::OKAY);
×
655
                    default:
656
                        // Repopulate the sniffs because some of them save their state
657
                        // and only clear it when the file changes, but we are rechecking
658
                        // the same file.
NEW
659
                        $file->ruleset->populateTokenListeners();
×
NEW
660
                        $file->reloadContent();
×
NEW
661
                        $file->process();
×
NEW
662
                        $this->reporter->cacheFileReport($file);
×
NEW
663
                        break;
×
664
                }
665
            }
666
        }
667

668
        // Clean up the file to save (a lot of) memory.
669
        $file->cleanUp();
×
670
    }
671

672

673
    /**
674
     * Waits for child processes to complete and cleans up after them.
675
     *
676
     * The reporting information returned by each child process is merged
677
     * into the main reporter class.
678
     *
679
     * @param array<int, string> $childProcs An array of child processes to wait for.
680
     *
681
     * @return bool
682
     */
683
    private function processChildProcs(array $childProcs)
×
684
    {
685
        $numProcessed = 0;
×
686
        $totalBatches = count($childProcs);
×
687

688
        $success = true;
×
689

690
        while (count($childProcs) > 0) {
×
691
            $pid = pcntl_waitpid(0, $status);
×
692
            if ($pid <= 0 || isset($childProcs[$pid]) === false) {
×
693
                // No child or a child with an unmanaged PID was returned.
694
                continue;
×
695
            }
696

697
            $childProcessStatus = pcntl_wexitstatus($status);
×
698
            if ($childProcessStatus !== 0) {
×
699
                $success = false;
×
700
            }
701

702
            $out = $childProcs[$pid];
×
703
            unset($childProcs[$pid]);
×
704
            if (file_exists($out) === false) {
×
705
                continue;
×
706
            }
707

708
            include $out;
×
709
            unlink($out);
×
710

711
            $numProcessed++;
×
712

713
            if (isset($childOutput) === false) {
×
714
                // The child process died, so the run has failed.
715
                $file = new DummyFile('', $this->ruleset, $this->config);
×
716
                $file->setErrorCounts(1, 0, 0, 0, 0, 0);
×
717
                $this->printProgress($file, $totalBatches, $numProcessed);
×
718
                $success = false;
×
719
                continue;
×
720
            }
721

722
            $this->reporter->totalFiles           += $childOutput['totalFiles'];
×
723
            $this->reporter->totalErrors          += $childOutput['totalErrors'];
×
724
            $this->reporter->totalWarnings        += $childOutput['totalWarnings'];
×
725
            $this->reporter->totalFixableErrors   += $childOutput['totalFixableErrors'];
×
726
            $this->reporter->totalFixableWarnings += $childOutput['totalFixableWarnings'];
×
727
            $this->reporter->totalFixedErrors     += $childOutput['totalFixedErrors'];
×
728
            $this->reporter->totalFixedWarnings   += $childOutput['totalFixedWarnings'];
×
729

730
            if (isset($debugOutput) === true) {
×
731
                echo $debugOutput;
×
732
            }
733

734
            if (isset($childCache) === true) {
×
735
                foreach ($childCache as $path => $cache) {
×
736
                    Cache::set($path, $cache);
×
737
                }
738
            }
739

740
            // Fake a processed file so we can print progress output for the batch.
741
            $file = new DummyFile('', $this->ruleset, $this->config);
×
742
            $file->setErrorCounts(
×
743
                $childOutput['totalErrors'],
×
744
                $childOutput['totalWarnings'],
×
745
                $childOutput['totalFixableErrors'],
×
746
                $childOutput['totalFixableWarnings'],
×
747
                $childOutput['totalFixedErrors'],
×
748
                $childOutput['totalFixedWarnings']
×
749
            );
750
            $this->printProgress($file, $totalBatches, $numProcessed);
×
751
        }
752

753
        return $success;
×
754
    }
755

756

757
    /**
758
     * Print progress information for a single processed file.
759
     *
760
     * @param \PHP_CodeSniffer\Files\File $file         The file that was processed.
761
     * @param int                         $numFiles     The total number of files to process.
762
     * @param int                         $numProcessed The number of files that have been processed,
763
     *                                                  including this one.
764
     *
765
     * @return void
766
     */
767
    public function printProgress(File $file, int $numFiles, int $numProcessed)
63✔
768
    {
769
        if (PHP_CODESNIFFER_VERBOSITY > 0
63✔
770
            || $this->config->showProgress === false
63✔
771
        ) {
772
            return;
3✔
773
        }
774

775
        $showColors  = $this->config->colors;
60✔
776
        $colorOpen   = '';
60✔
777
        $progressDot = '.';
60✔
778
        $colorClose  = '';
60✔
779

780
        // Show progress information.
781
        if ($file->ignored === true) {
60✔
782
            $progressDot = 'S';
3✔
783
        } else {
784
            $errors   = $file->getErrorCount();
60✔
785
            $warnings = $file->getWarningCount();
60✔
786
            $fixable  = $file->getFixableCount();
60✔
787
            $fixed    = ($file->getFixedErrorCount() + $file->getFixedWarningCount());
60✔
788

789
            if (PHP_CODESNIFFER_CBF === true) {
60✔
790
                // Files with fixed errors or warnings are F (green).
791
                // Files with unfixable errors or warnings are E (red).
792
                // Files with no errors or warnings are . (black).
793
                if ($fixable > 0) {
18✔
794
                    $progressDot = 'E';
6✔
795

796
                    if ($showColors === true) {
6✔
797
                        $colorOpen  = "\033[31m";
3✔
798
                        $colorClose = "\033[0m";
4✔
799
                    }
800
                } elseif ($fixed > 0) {
12✔
801
                    $progressDot = 'F';
6✔
802

803
                    if ($showColors === true) {
6✔
804
                        $colorOpen  = "\033[32m";
3✔
805
                        $colorClose = "\033[0m";
8✔
806
                    }
807
                }
808
            } else {
809
                // Files with errors are E (red).
810
                // Files with fixable errors are E (green).
811
                // Files with warnings are W (yellow).
812
                // Files with fixable warnings are W (green).
813
                // Files with no errors or warnings are . (black).
814
                if ($errors > 0) {
42✔
815
                    $progressDot = 'E';
9✔
816

817
                    if ($showColors === true) {
9✔
818
                        if ($fixable > 0) {
6✔
819
                            $colorOpen = "\033[32m";
3✔
820
                        } else {
821
                            $colorOpen = "\033[31m";
3✔
822
                        }
823

824
                        $colorClose = "\033[0m";
7✔
825
                    }
826
                } elseif ($warnings > 0) {
33✔
827
                    $progressDot = 'W';
9✔
828

829
                    if ($showColors === true) {
9✔
830
                        if ($fixable > 0) {
6✔
831
                            $colorOpen = "\033[32m";
3✔
832
                        } else {
833
                            $colorOpen = "\033[33m";
3✔
834
                        }
835

836
                        $colorClose = "\033[0m";
6✔
837
                    }
838
                }
839
            }
840
        }
841

842
        StatusWriter::write($colorOpen . $progressDot . $colorClose, 0, 0);
60✔
843

844
        $numPerLine = 60;
60✔
845
        if ($numProcessed !== $numFiles && ($numProcessed % $numPerLine) !== 0) {
60✔
846
            return;
60✔
847
        }
848

849
        $percent = round(($numProcessed / $numFiles) * 100);
18✔
850
        $padding = (strlen($numFiles) - strlen($numProcessed));
18✔
851
        if ($numProcessed === $numFiles
18✔
852
            && $numFiles > $numPerLine
18✔
853
            && ($numProcessed % $numPerLine) !== 0
18✔
854
        ) {
855
            $padding += ($numPerLine - ($numFiles - (floor($numFiles / $numPerLine) * $numPerLine)));
9✔
856
        }
857

858
        StatusWriter::write(str_repeat(' ', $padding) . " $numProcessed / $numFiles ($percent%)");
18✔
859
    }
6✔
860

861

862
    /**
863
     * Registers a PHP shutdown function to provide a more informative out of memory error.
864
     *
865
     * @param string $command The command which was used to initiate the PHPCS run.
866
     *
867
     * @return void
868
     */
869
    private function registerOutOfMemoryShutdownMessage(string $command)
×
870
    {
871
        // Allocate all needed memory beforehand as much as possible.
872
        $errorMsg    = PHP_EOL . 'The PHP_CodeSniffer "%1$s" command ran out of memory.' . PHP_EOL;
×
873
        $errorMsg   .= 'Either raise the "memory_limit" of PHP in the php.ini file or raise the memory limit at runtime' . PHP_EOL;
×
874
        $errorMsg   .= 'using `%1$s -d memory_limit=512M` (replace 512M with the desired memory limit).' . PHP_EOL;
×
875
        $errorMsg    = sprintf($errorMsg, $command);
×
876
        $memoryError = 'Allowed memory size of';
×
877
        $errorArray  = [
878
            'type'    => 42,
×
879
            'message' => 'Some random dummy string to take up memory and take up some more memory and some more',
880
            'file'    => 'Another random string, which would be a filename this time. Should be relatively long to allow for deeply nested files',
881
            'line'    => 31427,
882
        ];
883

884
        register_shutdown_function(
×
885
            static function () use (
886
                $errorMsg,
×
887
                $memoryError,
×
888
                $errorArray
×
889
            ) {
890
                $errorArray = error_get_last();
×
891
                if (is_array($errorArray) === true && strpos($errorArray['message'], $memoryError) !== false) {
×
892
                    fwrite(STDERR, $errorMsg);
×
893
                }
894
            }
×
895
        );
896
    }
897
}
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