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

PHPCSStandards / PHP_CodeSniffer / 14866218365

06 May 2025 05:43PM UTC coverage: 78.62% (+0.1%) from 78.472%
14866218365

Pull #123

github

web-flow
Merge 0ff1f1188 into 292322bf2
Pull Request #123: Improve handling of disable/enable/ignore directives

77 of 78 new or added lines in 3 files covered. (98.72%)

180 existing lines in 4 files now uncovered.

19622 of 24958 relevant lines covered (78.62%)

86.23 hits per line

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

20.67
/src/Runner.php
1
<?php
2
/**
3
 * Responsible for running PHPCS and PHPCBF.
4
 *
5
 * After creating an object of this class, you probably just want to
6
 * call runPHPCS() or runPHPCBF().
7
 *
8
 * @author    Greg Sherwood <gsherwood@squiz.net>
9
 * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
10
 * @license   https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
11
 */
12

13
namespace PHP_CodeSniffer;
14

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

29
class Runner
30
{
31

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

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

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

53

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

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

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

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

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

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

88
                return 0;
3✔
89
            }
90

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

102
                return 0;
5✔
103
            }
104

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

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

120
            $numErrors = $this->run();
×
121

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

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

139
            return $exitCode;
×
140
        }//end try
141

142
        if ($numErrors === 0) {
×
143
            // No errors found.
144
            return 0;
×
145
        } else if ($this->reporter->totalFixable === 0) {
×
146
            // Errors found, but none of them can be fixed by PHPCBF.
147
            return 1;
×
148
        } else {
149
            // Errors found, and some can be fixed by PHPCBF.
150
            return 2;
×
151
        }
152

153
    }//end runPHPCS()
154

155

156
    /**
157
     * Run the PHPCBF script.
158
     *
159
     * @return int
160
     */
161
    public function runPHPCBF()
×
162
    {
163
        $this->registerOutOfMemoryShutdownMessage('phpcbf');
×
164

165
        if (defined('PHP_CODESNIFFER_CBF') === false) {
×
166
            define('PHP_CODESNIFFER_CBF', true);
×
167
        }
168

169
        try {
170
            Timing::startTiming();
×
171

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

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

183
            // Init the run and load the rulesets to set additional config vars.
184
            $this->init();
×
185

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

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

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

209
            $this->config->reports = $newReports;
×
210

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

216
            $this->run();
×
217
            $this->reporter->printReports();
×
218

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

234
            return $exitCode;
×
235
        }//end try
236

237
        if ($this->reporter->totalFixed === 0) {
×
238
            // Nothing was fixed by PHPCBF.
239
            if ($this->reporter->totalFixable === 0) {
×
240
                // Nothing found that could be fixed.
241
                return 0;
×
242
            } else {
243
                // Something failed to fix.
244
                return 2;
×
245
            }
246
        }
247

248
        if ($this->reporter->totalFixable === 0) {
×
249
            // PHPCBF fixed all fixable errors.
250
            return 1;
×
251
        }
252

253
        // PHPCBF fixed some fixable errors, but others failed to fix.
254
        return 2;
×
255

256
    }//end runPHPCBF()
257

258

259
    /**
260
     * Init the rulesets and other high-level settings.
261
     *
262
     * @return void
263
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If a referenced standard is not installed.
264
     */
265
    public function init()
×
266
    {
267
        if (defined('PHP_CODESNIFFER_CBF') === false) {
×
268
            define('PHP_CODESNIFFER_CBF', false);
×
269
        }
270

271
        // Disable the PCRE JIT as this caused issues with parallel running.
272
        ini_set('pcre.jit', false);
×
273

274
        // Check that the standards are valid.
275
        foreach ($this->config->standards as $standard) {
×
276
            if (Standards::isInstalledStandard($standard) === false) {
×
277
                // They didn't select a valid coding standard, so help them
278
                // out by letting them know which standards are installed.
279
                $error  = 'ERROR: the "'.$standard.'" coding standard is not installed.'.PHP_EOL.PHP_EOL;
×
280
                $error .= Standards::prepareInstalledStandardsForDisplay().PHP_EOL;
×
281
                throw new DeepExitException($error, 3);
×
282
            }
283
        }
284

285
        // Saves passing the Config object into other objects that only need
286
        // the verbosity flag for debug output.
287
        if (defined('PHP_CODESNIFFER_VERBOSITY') === false) {
×
288
            define('PHP_CODESNIFFER_VERBOSITY', $this->config->verbosity);
×
289
        }
290

291
        // Create this class so it is autoloaded and sets up a bunch
292
        // of PHP_CodeSniffer-specific token type constants.
293
        new Tokens();
×
294

295
        // Allow autoloading of custom files inside installed standards.
296
        $installedStandards = Standards::getInstalledStandardDetails();
×
297
        foreach ($installedStandards as $details) {
×
298
            Autoload::addSearchPath($details['path'], $details['namespace']);
×
299
        }
300

301
        // The ruleset contains all the information about how the files
302
        // should be checked and/or fixed.
303
        try {
304
            $this->ruleset = new Ruleset($this->config);
×
305

306
            if ($this->ruleset->hasSniffDeprecations() === true) {
×
307
                $this->ruleset->showSniffDeprecations();
×
308
            }
309
        } catch (RuntimeException $e) {
×
310
            $error  = rtrim($e->getMessage(), "\r\n").PHP_EOL.PHP_EOL;
×
311
            $error .= $this->config->printShortUsage(true);
×
312
            throw new DeepExitException($error, 3);
×
313
        }
314

315
    }//end init()
316

317

318
    /**
319
     * Performs the run.
320
     *
321
     * @return int The number of errors and warnings found.
322
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
323
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException
324
     */
325
    private function run()
12✔
326
    {
327
        // The class that manages all reporters for the run.
328
        $this->reporter = new Reporter($this->config);
12✔
329

330
        // Include bootstrap files.
331
        foreach ($this->config->bootstrap as $bootstrap) {
12✔
332
            include $bootstrap;
×
333
        }
334

335
        if ($this->config->stdin === true) {
12✔
336
            $fileContents = $this->config->stdinContent;
×
337
            if ($fileContents === null) {
×
338
                $handle = fopen('php://stdin', 'r');
×
339
                stream_set_blocking($handle, true);
×
340
                $fileContents = stream_get_contents($handle);
×
341
                fclose($handle);
×
342
            }
343

344
            $todo  = new FileList($this->config, $this->ruleset);
×
345
            $dummy = new DummyFile($fileContents, $this->ruleset, $this->config);
×
346
            $todo->addFile($dummy->path, $dummy);
×
347
        } else {
348
            if (empty($this->config->files) === true) {
12✔
349
                $error  = 'ERROR: You must supply at least one file or directory to process.'.PHP_EOL.PHP_EOL;
×
350
                $error .= $this->config->printShortUsage(true);
×
351
                throw new DeepExitException($error, 3);
×
352
            }
353

354
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
12✔
355
                StatusWriter::write('Creating file list... ', 0, 0);
×
356
            }
357

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

360
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
12✔
361
                $numFiles = count($todo);
×
362
                StatusWriter::write("DONE ($numFiles files in queue)");
×
363
            }
364

365
            if ($this->config->cache === true) {
12✔
366
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
367
                    StatusWriter::write('Loading cache... ', 0, 0);
×
368
                }
369

370
                Cache::load($this->ruleset, $this->config);
×
371

372
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
373
                    $size = Cache::getSize();
×
374
                    StatusWriter::write("DONE ($size files in cache)");
×
375
                }
376
            }
377
        }//end if
378

379
        $numFiles = count($todo);
12✔
380
        if ($numFiles === 0) {
12✔
381
            $error  = 'ERROR: No files were checked.'.PHP_EOL;
12✔
382
            $error .= 'All specified files were excluded or did not match filtering rules.'.PHP_EOL.PHP_EOL;
12✔
383
            throw new DeepExitException($error, 3);
12✔
384
        }
385

386
        // Turn all sniff errors into exceptions.
387
        set_error_handler([$this, 'handleErrors']);
×
388

389
        // If verbosity is too high, turn off parallelism so the
390
        // debug output is clean.
391
        if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
392
            $this->config->parallel = 1;
×
393
        }
394

395
        // If the PCNTL extension isn't installed, we can't fork.
396
        if (function_exists('pcntl_fork') === false) {
×
397
            $this->config->parallel = 1;
×
398
        }
399

400
        $lastDir = '';
×
401

402
        if ($this->config->parallel === 1) {
×
403
            // Running normally.
404
            $numProcessed = 0;
×
405
            foreach ($todo as $path => $file) {
×
406
                if ($file->ignored === false) {
×
407
                    $currDir = dirname($path);
×
408
                    if ($lastDir !== $currDir) {
×
409
                        if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
410
                            StatusWriter::write('Changing into directory '.Common::stripBasepath($currDir, $this->config->basepath));
×
411
                        }
412

413
                        $lastDir = $currDir;
×
414
                    }
415

416
                    $this->processFile($file);
×
417
                } else if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
418
                    StatusWriter::write('Skipping '.basename($file->path));
×
419
                }
420

421
                $numProcessed++;
×
422
                $this->printProgress($file, $numFiles, $numProcessed);
×
423
            }
424
        } else {
425
            // Batching and forking.
426
            $childProcs  = [];
×
427
            $numPerBatch = ceil($numFiles / $this->config->parallel);
×
428

429
            for ($batch = 0; $batch < $this->config->parallel; $batch++) {
×
430
                $startAt = ($batch * $numPerBatch);
×
431
                if ($startAt >= $numFiles) {
×
432
                    break;
×
433
                }
434

435
                $endAt = ($startAt + $numPerBatch);
×
436
                if ($endAt > $numFiles) {
×
437
                    $endAt = $numFiles;
×
438
                }
439

440
                $childOutFilename = tempnam(sys_get_temp_dir(), 'phpcs-child');
×
441
                $pid = pcntl_fork();
×
442
                if ($pid === -1) {
×
443
                    throw new RuntimeException('Failed to create child process');
×
444
                } else if ($pid !== 0) {
×
445
                    $childProcs[$pid] = $childOutFilename;
×
446
                } else {
447
                    // Move forward to the start of the batch.
448
                    $todo->rewind();
×
449
                    for ($i = 0; $i < $startAt; $i++) {
×
450
                        $todo->next();
×
451
                    }
452

453
                    // Reset the reporter to make sure only figures from this
454
                    // file batch are recorded.
455
                    $this->reporter->totalFiles    = 0;
×
456
                    $this->reporter->totalErrors   = 0;
×
457
                    $this->reporter->totalWarnings = 0;
×
458
                    $this->reporter->totalFixable  = 0;
×
459
                    $this->reporter->totalFixed    = 0;
×
460

461
                    // Process the files.
462
                    $pathsProcessed = [];
×
463
                    ob_start();
×
464
                    for ($i = $startAt; $i < $endAt; $i++) {
×
465
                        $path = $todo->key();
×
466
                        $file = $todo->current();
×
467

468
                        if ($file->ignored === true) {
×
469
                            $todo->next();
×
470
                            continue;
×
471
                        }
472

473
                        $currDir = dirname($path);
×
474
                        if ($lastDir !== $currDir) {
×
475
                            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
476
                                StatusWriter::write('Changing into directory '.Common::stripBasepath($currDir, $this->config->basepath));
×
477
                            }
478

479
                            $lastDir = $currDir;
×
480
                        }
481

482
                        $this->processFile($file);
×
483

484
                        $pathsProcessed[] = $path;
×
485
                        $todo->next();
×
486
                    }//end for
487

488
                    $debugOutput = ob_get_contents();
×
489
                    ob_end_clean();
×
490

491
                    // Write information about the run to the filesystem
492
                    // so it can be picked up by the main process.
493
                    $childOutput = [
494
                        'totalFiles'    => $this->reporter->totalFiles,
×
495
                        'totalErrors'   => $this->reporter->totalErrors,
×
496
                        'totalWarnings' => $this->reporter->totalWarnings,
×
497
                        'totalFixable'  => $this->reporter->totalFixable,
×
498
                        'totalFixed'    => $this->reporter->totalFixed,
×
499
                    ];
500

501
                    $output  = '<'.'?php'."\n".' $childOutput = ';
×
502
                    $output .= var_export($childOutput, true);
×
503
                    $output .= ";\n\$debugOutput = ";
×
504
                    $output .= var_export($debugOutput, true);
×
505

506
                    if ($this->config->cache === true) {
×
507
                        $childCache = [];
×
508
                        foreach ($pathsProcessed as $path) {
×
509
                            $childCache[$path] = Cache::get($path);
×
510
                        }
511

512
                        $output .= ";\n\$childCache = ";
×
513
                        $output .= var_export($childCache, true);
×
514
                    }
515

516
                    $output .= ";\n?".'>';
×
517
                    file_put_contents($childOutFilename, $output);
×
518
                    exit();
×
519
                }//end if
520
            }//end for
521

522
            $success = $this->processChildProcs($childProcs);
×
523
            if ($success === false) {
×
524
                throw new RuntimeException('One or more child processes failed to run');
×
525
            }
526
        }//end if
527

528
        restore_error_handler();
×
529

530
        if (PHP_CODESNIFFER_VERBOSITY === 0
×
531
            && $this->config->interactive === false
×
532
            && $this->config->showProgress === true
×
533
        ) {
534
            StatusWriter::writeNewline(2);
×
535
        }
536

537
        if ($this->config->cache === true) {
×
538
            Cache::save();
×
539
        }
540

541
        $ignoreWarnings = Config::getConfigData('ignore_warnings_on_exit');
×
542
        $ignoreErrors   = Config::getConfigData('ignore_errors_on_exit');
×
543

544
        $return = ($this->reporter->totalErrors + $this->reporter->totalWarnings);
×
545
        if ($ignoreErrors !== null) {
×
546
            $ignoreErrors = (bool) $ignoreErrors;
×
547
            if ($ignoreErrors === true) {
×
548
                $return -= $this->reporter->totalErrors;
×
549
            }
550
        }
551

552
        if ($ignoreWarnings !== null) {
×
553
            $ignoreWarnings = (bool) $ignoreWarnings;
×
554
            if ($ignoreWarnings === true) {
×
555
                $return -= $this->reporter->totalWarnings;
×
556
            }
557
        }
558

559
        return $return;
×
560

561
    }//end run()
562

563

564
    /**
565
     * Converts all PHP errors into exceptions.
566
     *
567
     * This method forces a sniff to stop processing if it is not
568
     * able to handle a specific piece of code, instead of continuing
569
     * and potentially getting into a loop.
570
     *
571
     * @param int    $code    The level of error raised.
572
     * @param string $message The error message.
573
     * @param string $file    The path of the file that raised the error.
574
     * @param int    $line    The line number the error was raised at.
575
     *
576
     * @return bool
577
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException
578
     */
579
    public function handleErrors($code, $message, $file, $line)
×
580
    {
581
        if ((error_reporting() & $code) === 0) {
×
582
            // This type of error is being muted.
583
            return true;
×
584
        }
585

586
        throw new RuntimeException("$message in $file on line $line");
×
587

588
    }//end handleErrors()
589

590

591
    /**
592
     * Processes a single file, including checking and fixing.
593
     *
594
     * @param \PHP_CodeSniffer\Files\File $file The file to be processed.
595
     *
596
     * @return void
597
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
598
     */
599
    public function processFile($file)
×
600
    {
601
        if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
602
            $startTime = microtime(true);
×
603
            $newlines  = 0;
×
604
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
605
                $newlines = 1;
×
606
            }
607

608
            StatusWriter::write('Processing '.basename($file->path).' ', 0, $newlines);
×
609
        }
610

611
        try {
612
            $file->process();
×
613

614
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
615
                StatusWriter::write('DONE in '.Timing::getHumanReadableDuration(Timing::getDurationSince($startTime)), 0, 0);
×
616

617
                if (PHP_CODESNIFFER_CBF === true) {
×
618
                    $errors = $file->getFixableCount();
×
UNCOV
619
                    StatusWriter::write(" ($errors fixable violations)");
×
620
                } else {
621
                    $errors   = $file->getErrorCount();
×
UNCOV
622
                    $warnings = $file->getWarningCount();
×
UNCOV
623
                    StatusWriter::write(" ($errors errors, $warnings warnings)");
×
624
                }
625
            }
626
        } catch (Exception $e) {
×
UNCOV
627
            $error = 'An error occurred during processing; checking has been aborted. The error message was: '.$e->getMessage();
×
628

629
            // Determine which sniff caused the error.
630
            $sniffStack = null;
×
UNCOV
631
            $nextStack  = null;
×
UNCOV
632
            foreach ($e->getTrace() as $step) {
×
633
                if (isset($step['file']) === false) {
×
634
                    continue;
×
635
                }
636

637
                if (empty($sniffStack) === false) {
×
638
                    $nextStack = $step;
×
639
                    break;
×
640
                }
641

UNCOV
642
                if (substr($step['file'], -9) === 'Sniff.php') {
×
UNCOV
643
                    $sniffStack = $step;
×
644
                    continue;
×
645
                }
646
            }
647

UNCOV
648
            if (empty($sniffStack) === false) {
×
649
                $sniffCode = '';
×
650
                try {
651
                    if (empty($nextStack) === false
×
UNCOV
652
                        && isset($nextStack['class']) === true
×
653
                    ) {
UNCOV
654
                        $sniffCode = 'the '.Common::getSniffCode($nextStack['class']).' sniff';
×
655
                    }
656
                } catch (InvalidArgumentException $e) {
×
657
                    // Sniff code could not be determined. This may be an abstract sniff class.
658
                }
659

UNCOV
660
                if ($sniffCode === '') {
×
661
                    $sniffCode = substr(strrchr(str_replace('\\', '/', $sniffStack['file']), '/'), 1);
×
662
                }
663

UNCOV
664
                $error .= sprintf(PHP_EOL.'The error originated in %s on line %s.', $sniffCode, $sniffStack['line']);
×
665
            }
666

667
            $file->addErrorOnLine($error, 1, 'Internal.Exception');
×
668
        }//end try
669

UNCOV
670
        $this->reporter->cacheFileReport($file);
×
671

UNCOV
672
        if ($this->config->interactive === true) {
×
673
            /*
674
                Running interactively.
675
                Print the error report for the current file and then wait for user input.
676
            */
677

678
            // Get current violations and then clear the list to make sure
679
            // we only print violations for a single file each time.
UNCOV
680
            $numErrors = null;
×
UNCOV
681
            while ($numErrors !== 0) {
×
UNCOV
682
                $numErrors = ($file->getErrorCount() + $file->getWarningCount());
×
UNCOV
683
                if ($numErrors === 0) {
×
UNCOV
684
                    continue;
×
685
                }
686

687
                $this->reporter->printReport('full');
×
688

689
                echo '<ENTER> to recheck, [s] to skip or [q] to quit : ';
×
690
                $input = fgets(STDIN);
×
691
                $input = trim($input);
×
692

693
                switch ($input) {
694
                case 's':
×
UNCOV
695
                    break(2);
×
696
                case 'q':
×
697
                    throw new DeepExitException('', 0);
×
698
                default:
699
                    // Repopulate the sniffs because some of them save their state
700
                    // and only clear it when the file changes, but we are rechecking
701
                    // the same file.
702
                    $file->ruleset->populateTokenListeners();
×
703
                    $file->reloadContent();
×
704
                    $file->process();
×
UNCOV
705
                    $this->reporter->cacheFileReport($file);
×
UNCOV
706
                    break;
×
707
                }
708
            }//end while
709
        }//end if
710

711
        // Clean up the file to save (a lot of) memory.
712
        $file->cleanUp();
×
713

714
    }//end processFile()
715

716

717
    /**
718
     * Waits for child processes to complete and cleans up after them.
719
     *
720
     * The reporting information returned by each child process is merged
721
     * into the main reporter class.
722
     *
723
     * @param array $childProcs An array of child processes to wait for.
724
     *
725
     * @return bool
726
     */
UNCOV
727
    private function processChildProcs($childProcs)
×
728
    {
UNCOV
729
        $numProcessed = 0;
×
UNCOV
730
        $totalBatches = count($childProcs);
×
731

UNCOV
732
        $success = true;
×
733

734
        while (count($childProcs) > 0) {
×
UNCOV
735
            $pid = pcntl_waitpid(0, $status);
×
736
            if ($pid <= 0) {
×
737
                continue;
×
738
            }
739

UNCOV
740
            $childProcessStatus = pcntl_wexitstatus($status);
×
741
            if ($childProcessStatus !== 0) {
×
742
                $success = false;
×
743
            }
744

UNCOV
745
            $out = $childProcs[$pid];
×
UNCOV
746
            unset($childProcs[$pid]);
×
747
            if (file_exists($out) === false) {
×
748
                continue;
×
749
            }
750

UNCOV
751
            include $out;
×
752
            unlink($out);
×
753

754
            $numProcessed++;
×
755

UNCOV
756
            if (isset($childOutput) === false) {
×
757
                // The child process died, so the run has failed.
758
                $file = new DummyFile('', $this->ruleset, $this->config);
×
759
                $file->setErrorCounts(1, 0, 0, 0);
×
UNCOV
760
                $this->printProgress($file, $totalBatches, $numProcessed);
×
761
                $success = false;
×
UNCOV
762
                continue;
×
763
            }
764

765
            $this->reporter->totalFiles    += $childOutput['totalFiles'];
×
766
            $this->reporter->totalErrors   += $childOutput['totalErrors'];
×
767
            $this->reporter->totalWarnings += $childOutput['totalWarnings'];
×
768
            $this->reporter->totalFixable  += $childOutput['totalFixable'];
×
769
            $this->reporter->totalFixed    += $childOutput['totalFixed'];
×
770

UNCOV
771
            if (isset($debugOutput) === true) {
×
772
                echo $debugOutput;
×
773
            }
774

775
            if (isset($childCache) === true) {
×
776
                foreach ($childCache as $path => $cache) {
×
UNCOV
777
                    Cache::set($path, $cache);
×
778
                }
779
            }
780

781
            // Fake a processed file so we can print progress output for the batch.
782
            $file = new DummyFile('', $this->ruleset, $this->config);
×
783
            $file->setErrorCounts(
×
784
                $childOutput['totalErrors'],
×
UNCOV
785
                $childOutput['totalWarnings'],
×
UNCOV
786
                $childOutput['totalFixable'],
×
UNCOV
787
                $childOutput['totalFixed']
×
788
            );
789
            $this->printProgress($file, $totalBatches, $numProcessed);
×
790
        }//end while
791

792
        return $success;
×
793

794
    }//end processChildProcs()
795

796

797
    /**
798
     * Print progress information for a single processed file.
799
     *
800
     * @param \PHP_CodeSniffer\Files\File $file         The file that was processed.
801
     * @param int                         $numFiles     The total number of files to process.
802
     * @param int                         $numProcessed The number of files that have been processed,
803
     *                                                  including this one.
804
     *
805
     * @return void
806
     */
807
    public function printProgress(File $file, $numFiles, $numProcessed)
63✔
808
    {
809
        if (PHP_CODESNIFFER_VERBOSITY > 0
63✔
810
            || $this->config->showProgress === false
63✔
811
        ) {
812
            return;
3✔
813
        }
814

815
        $showColors  = $this->config->colors;
60✔
816
        $colorOpen   = '';
60✔
817
        $progressDot = '.';
60✔
818
        $colorClose  = '';
60✔
819

820
        // Show progress information.
821
        if ($file->ignored === true) {
60✔
822
            $progressDot = 'S';
3✔
823
        } else {
824
            $errors   = $file->getErrorCount();
60✔
825
            $warnings = $file->getWarningCount();
60✔
826
            $fixable  = $file->getFixableCount();
60✔
827
            $fixed    = $file->getFixedCount();
60✔
828

829
            if (PHP_CODESNIFFER_CBF === true) {
60✔
830
                // Files with fixed errors or warnings are F (green).
831
                // Files with unfixable errors or warnings are E (red).
832
                // Files with no errors or warnings are . (black).
833
                if ($fixable > 0) {
18✔
834
                    $progressDot = 'E';
6✔
835

836
                    if ($showColors === true) {
6✔
837
                        $colorOpen  = "\033[31m";
3✔
838
                        $colorClose = "\033[0m";
5✔
839
                    }
840
                } else if ($fixed > 0) {
12✔
841
                    $progressDot = 'F';
6✔
842

843
                    if ($showColors === true) {
6✔
844
                        $colorOpen  = "\033[32m";
3✔
845
                        $colorClose = "\033[0m";
13✔
846
                    }
847
                }//end if
848
            } else {
849
                // Files with errors are E (red).
850
                // Files with fixable errors are E (green).
851
                // Files with warnings are W (yellow).
852
                // Files with fixable warnings are W (green).
853
                // Files with no errors or warnings are . (black).
854
                if ($errors > 0) {
42✔
855
                    $progressDot = 'E';
9✔
856

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

864
                        $colorClose = "\033[0m";
8✔
865
                    }
866
                } else if ($warnings > 0) {
33✔
867
                    $progressDot = 'W';
9✔
868

869
                    if ($showColors === true) {
9✔
870
                        if ($fixable > 0) {
6✔
871
                            $colorOpen = "\033[32m";
3✔
872
                        } else {
873
                            $colorOpen = "\033[33m";
3✔
874
                        }
875

876
                        $colorClose = "\033[0m";
6✔
877
                    }
878
                }//end if
879
            }//end if
880
        }//end if
881

882
        StatusWriter::write($colorOpen.$progressDot.$colorClose, 0, 0);
60✔
883

884
        $numPerLine = 60;
60✔
885
        if ($numProcessed !== $numFiles && ($numProcessed % $numPerLine) !== 0) {
60✔
886
            return;
60✔
887
        }
888

889
        $percent = round(($numProcessed / $numFiles) * 100);
18✔
890
        $padding = (strlen($numFiles) - strlen($numProcessed));
18✔
891
        if ($numProcessed === $numFiles
18✔
892
            && $numFiles > $numPerLine
18✔
893
            && ($numProcessed % $numPerLine) !== 0
18✔
894
        ) {
895
            $padding += ($numPerLine - ($numFiles - (floor($numFiles / $numPerLine) * $numPerLine)));
9✔
896
        }
897

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

900
    }//end printProgress()
6✔
901

902

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

UNCOV
925
        register_shutdown_function(
×
926
            static function () use (
UNCOV
927
                $errorMsg,
×
UNCOV
928
                $memoryError,
×
UNCOV
929
                $errorArray
×
930
            ) {
UNCOV
931
                $errorArray = error_get_last();
×
932
                if (is_array($errorArray) === true && strpos($errorArray['message'], $memoryError) !== false) {
×
UNCOV
933
                    fwrite(STDERR, $errorMsg);
×
934
                }
935
            }
×
936
        );
937

938
    }//end registerOutOfMemoryShutdownMessage()
939

940

941
}//end class
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc