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

PHPCSStandards / PHP_CodeSniffer / 15253296250

26 May 2025 11:55AM UTC coverage: 78.632% (+0.3%) from 78.375%
15253296250

Pull #1105

github

web-flow
Merge d9441d98f into caf806050
Pull Request #1105: Skip tests when 'git' command is not available

19665 of 25009 relevant lines covered (78.63%)

88.67 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
        }//end try
142

143
        return ExitCode::calculate($this->reporter);
×
144

145
    }//end runPHPCS()
146

147

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

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

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

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

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

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

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

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

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

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

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

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

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

226
            return $exitCode;
×
227
        }//end try
228

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

231
    }//end runPHPCBF()
232

233

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

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

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

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

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

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

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

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

290
    }//end init()
291

292

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

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

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

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

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

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

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

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

346
                Cache::load($this->ruleset, $this->config);
×
347

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

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

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

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

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

376
        $lastDir = '';
×
377

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

389
                        $lastDir = $currDir;
×
390
                    }
391

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

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

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

411
                $endAt = ($startAt + $numPerBatch);
×
412
                if ($endAt > $numFiles) {
×
413
                    $endAt = $numFiles;
×
414
                }
415

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

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

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

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

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

457
                            $lastDir = $currDir;
×
458
                        }
459

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

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

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

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

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

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

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

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

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

508
        restore_error_handler();
×
509

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

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

521
    }//end run()
522

523

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

546
        throw new RuntimeException("$message in $file on line $line");
×
547

548
    }//end handleErrors()
549

550

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

568
            StatusWriter::write('Processing '.basename($file->path).' ', 0, $newlines);
×
569
        }
570

571
        try {
572
            $file->process();
×
573

574
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
575
                StatusWriter::write('DONE in '.Timing::getHumanReadableDuration(Timing::getDurationSince($startTime)), 0, 0);
×
576

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

590
            // Determine which sniff caused the error.
591
            $sniffStack = null;
×
592
            $nextStack  = null;
×
593
            foreach ($e->getTrace() as $step) {
×
594
                if (isset($step['file']) === false) {
×
595
                    continue;
×
596
                }
597

598
                if (empty($sniffStack) === false) {
×
599
                    $nextStack = $step;
×
600
                    break;
×
601
                }
602

603
                if (substr($step['file'], -9) === 'Sniff.php') {
×
604
                    $sniffStack = $step;
×
605
                    continue;
×
606
                }
607
            }
608

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

621
                if ($sniffCode === '') {
×
622
                    $sniffCode = substr(strrchr(str_replace('\\', '/', $sniffStack['file']), '/'), 1);
×
623
                }
624

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

628
            $file->addErrorOnLine($error, 1, 'Internal.Exception');
×
629
        }//end try
630

631
        $this->reporter->cacheFileReport($file);
×
632

633
        if ($this->config->interactive === true) {
×
634
            /*
635
                Running interactively.
636
                Print the error report for the current file and then wait for user input.
637
            */
638

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

648
                $this->reporter->printReport('full');
×
649

650
                echo '<ENTER> to recheck, [s] to skip or [q] to quit : ';
×
651
                $input = fgets(STDIN);
×
652
                $input = trim($input);
×
653

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

673
        // Clean up the file to save (a lot of) memory.
674
        $file->cleanUp();
×
675

676
    }//end processFile()
677

678

679
    /**
680
     * Waits for child processes to complete and cleans up after them.
681
     *
682
     * The reporting information returned by each child process is merged
683
     * into the main reporter class.
684
     *
685
     * @param array $childProcs An array of child processes to wait for.
686
     *
687
     * @return bool
688
     */
689
    private function processChildProcs($childProcs)
×
690
    {
691
        $numProcessed = 0;
×
692
        $totalBatches = count($childProcs);
×
693

694
        $success = true;
×
695

696
        while (count($childProcs) > 0) {
×
697
            $pid = pcntl_waitpid(0, $status);
×
698
            if ($pid <= 0) {
×
699
                continue;
×
700
            }
701

702
            $childProcessStatus = pcntl_wexitstatus($status);
×
703
            if ($childProcessStatus !== 0) {
×
704
                $success = false;
×
705
            }
706

707
            $out = $childProcs[$pid];
×
708
            unset($childProcs[$pid]);
×
709
            if (file_exists($out) === false) {
×
710
                continue;
×
711
            }
712

713
            include $out;
×
714
            unlink($out);
×
715

716
            $numProcessed++;
×
717

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

727
            $this->reporter->totalFiles           += $childOutput['totalFiles'];
×
728
            $this->reporter->totalErrors          += $childOutput['totalErrors'];
×
729
            $this->reporter->totalWarnings        += $childOutput['totalWarnings'];
×
730
            $this->reporter->totalFixableErrors   += $childOutput['totalFixableErrors'];
×
731
            $this->reporter->totalFixableWarnings += $childOutput['totalFixableWarnings'];
×
732
            $this->reporter->totalFixedErrors     += $childOutput['totalFixedErrors'];
×
733
            $this->reporter->totalFixedWarnings   += $childOutput['totalFixedWarnings'];
×
734

735
            if (isset($debugOutput) === true) {
×
736
                echo $debugOutput;
×
737
            }
738

739
            if (isset($childCache) === true) {
×
740
                foreach ($childCache as $path => $cache) {
×
741
                    Cache::set($path, $cache);
×
742
                }
743
            }
744

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

758
        return $success;
×
759

760
    }//end processChildProcs()
761

762

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

781
        $showColors  = $this->config->colors;
60✔
782
        $colorOpen   = '';
60✔
783
        $progressDot = '.';
60✔
784
        $colorClose  = '';
60✔
785

786
        // Show progress information.
787
        if ($file->ignored === true) {
60✔
788
            $progressDot = 'S';
3✔
789
        } else {
790
            $errors   = $file->getErrorCount();
60✔
791
            $warnings = $file->getWarningCount();
60✔
792
            $fixable  = $file->getFixableCount();
60✔
793
            $fixed    = $file->getFixedCount();
60✔
794

795
            if (PHP_CODESNIFFER_CBF === true) {
60✔
796
                // Files with fixed errors or warnings are F (green).
797
                // Files with unfixable errors or warnings are E (red).
798
                // Files with no errors or warnings are . (black).
799
                if ($fixable > 0) {
18✔
800
                    $progressDot = 'E';
6✔
801

802
                    if ($showColors === true) {
6✔
803
                        $colorOpen  = "\033[31m";
3✔
804
                        $colorClose = "\033[0m";
4✔
805
                    }
806
                } else if ($fixed > 0) {
12✔
807
                    $progressDot = 'F';
6✔
808

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

823
                    if ($showColors === true) {
9✔
824
                        if ($fixable > 0) {
6✔
825
                            $colorOpen = "\033[32m";
3✔
826
                        } else {
827
                            $colorOpen = "\033[31m";
3✔
828
                        }
829

830
                        $colorClose = "\033[0m";
7✔
831
                    }
832
                } else if ($warnings > 0) {
33✔
833
                    $progressDot = 'W';
9✔
834

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

842
                        $colorClose = "\033[0m";
6✔
843
                    }
844
                }//end if
845
            }//end if
846
        }//end if
847

848
        StatusWriter::write($colorOpen.$progressDot.$colorClose, 0, 0);
60✔
849

850
        $numPerLine = 60;
60✔
851
        if ($numProcessed !== $numFiles && ($numProcessed % $numPerLine) !== 0) {
60✔
852
            return;
60✔
853
        }
854

855
        $percent = round(($numProcessed / $numFiles) * 100);
18✔
856
        $padding = (strlen($numFiles) - strlen($numProcessed));
18✔
857
        if ($numProcessed === $numFiles
18✔
858
            && $numFiles > $numPerLine
18✔
859
            && ($numProcessed % $numPerLine) !== 0
18✔
860
        ) {
861
            $padding += ($numPerLine - ($numFiles - (floor($numFiles / $numPerLine) * $numPerLine)));
9✔
862
        }
863

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

866
    }//end printProgress()
6✔
867

868

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

891
        register_shutdown_function(
×
892
            static function () use (
893
                $errorMsg,
×
894
                $memoryError,
×
895
                $errorArray
×
896
            ) {
897
                $errorArray = error_get_last();
×
898
                if (is_array($errorArray) === true && strpos($errorArray['message'], $memoryError) !== false) {
×
899
                    fwrite(STDERR, $errorMsg);
×
900
                }
901
            }
×
902
        );
903

904
    }//end registerOutOfMemoryShutdownMessage()
905

906

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

© 2025 Coveralls, Inc