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

PHPCSStandards / PHP_CodeSniffer / 7326289291

26 Dec 2023 03:26AM UTC coverage: 64.019% (+0.003%) from 64.016%
7326289291

push

github

jrfnl
Runner::processFile(): remove stray passed params

The `Reporter::cacheFileReport()` method only takes one parameter.

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

1 existing line in 1 file now uncovered.

15127 of 23629 relevant lines covered (64.02%)

5.38 hits per line

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

0.0
/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 PHP_CodeSniffer\Exceptions\DeepExitException;
16
use PHP_CodeSniffer\Exceptions\RuntimeException;
17
use PHP_CodeSniffer\Files\DummyFile;
18
use PHP_CodeSniffer\Files\File;
19
use PHP_CodeSniffer\Files\FileList;
20
use PHP_CodeSniffer\Util\Cache;
21
use PHP_CodeSniffer\Util\Common;
22
use PHP_CodeSniffer\Util\Standards;
23

24
class Runner
25
{
26

27
    /**
28
     * The config data for the run.
29
     *
30
     * @var \PHP_CodeSniffer\Config
31
     */
32
    public $config = null;
33

34
    /**
35
     * The ruleset used for the run.
36
     *
37
     * @var \PHP_CodeSniffer\Ruleset
38
     */
39
    public $ruleset = null;
40

41
    /**
42
     * The reporter used for generating reports after the run.
43
     *
44
     * @var \PHP_CodeSniffer\Reporter
45
     */
46
    public $reporter = null;
47

48

49
    /**
50
     * Run the PHPCS script.
51
     *
52
     * @return int
53
     */
54
    public function runPHPCS()
×
55
    {
56
        $this->registerOutOfMemoryShutdownMessage('phpcs');
×
57

58
        try {
59
            Util\Timing::startTiming();
×
60
            Runner::checkRequirements();
×
61

62
            if (defined('PHP_CODESNIFFER_CBF') === false) {
×
63
                define('PHP_CODESNIFFER_CBF', false);
×
64
            }
65

66
            // Creating the Config object populates it with all required settings
67
            // based on the CLI arguments provided to the script and any config
68
            // values the user has set.
69
            $this->config = new Config();
×
70

71
            // Init the run and load the rulesets to set additional config vars.
72
            $this->init();
×
73

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

84
                return 0;
×
85
            }
86

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

98
                return 0;
×
99
            }
100

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

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

116
            $numErrors = $this->run();
×
117

118
            // Print all the reports for this run.
119
            $this->reporter->printReports();
×
120

121
            Util\Timing::printRunTime();
×
122
        } catch (DeepExitException $e) {
×
123
            echo $e->getMessage();
×
124
            return $e->getCode();
×
125
        }//end try
126

127
        if ($numErrors === 0) {
×
128
            // No errors found.
129
            return 0;
×
130
        } else if ($this->reporter->totalFixable === 0) {
×
131
            // Errors found, but none of them can be fixed by PHPCBF.
132
            return 1;
×
133
        } else {
134
            // Errors found, and some can be fixed by PHPCBF.
135
            return 2;
×
136
        }
137

138
    }//end runPHPCS()
139

140

141
    /**
142
     * Run the PHPCBF script.
143
     *
144
     * @return int
145
     */
146
    public function runPHPCBF()
×
147
    {
148
        $this->registerOutOfMemoryShutdownMessage('phpcbf');
×
149

150
        if (defined('PHP_CODESNIFFER_CBF') === false) {
×
151
            define('PHP_CODESNIFFER_CBF', true);
×
152
        }
153

154
        try {
155
            Util\Timing::startTiming();
×
156
            Runner::checkRequirements();
×
157

158
            // Creating the Config object populates it with all required settings
159
            // based on the CLI arguments provided to the script and any config
160
            // values the user has set.
161
            $this->config = new Config();
×
162

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

169
            // Init the run and load the rulesets to set additional config vars.
170
            $this->init();
×
171

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

179
            // Override some of the command line settings that might break the fixes.
180
            $this->config->generator    = null;
×
181
            $this->config->explain      = false;
×
182
            $this->config->interactive  = false;
×
183
            $this->config->cache        = false;
×
184
            $this->config->showSources  = false;
×
185
            $this->config->recordErrors = false;
×
186
            $this->config->reportFile   = null;
×
187
            $this->config->reports      = ['cbf' => null];
×
188

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

194
            $this->run();
×
195
            $this->reporter->printReports();
×
196

197
            echo PHP_EOL;
×
198
            Util\Timing::printRunTime();
×
199
        } catch (DeepExitException $e) {
×
200
            echo $e->getMessage();
×
201
            return $e->getCode();
×
202
        }//end try
203

204
        if ($this->reporter->totalFixed === 0) {
×
205
            // Nothing was fixed by PHPCBF.
206
            if ($this->reporter->totalFixable === 0) {
×
207
                // Nothing found that could be fixed.
208
                return 0;
×
209
            } else {
210
                // Something failed to fix.
211
                return 2;
×
212
            }
213
        }
214

215
        if ($this->reporter->totalFixable === 0) {
×
216
            // PHPCBF fixed all fixable errors.
217
            return 1;
×
218
        }
219

220
        // PHPCBF fixed some fixable errors, but others failed to fix.
221
        return 2;
×
222

223
    }//end runPHPCBF()
224

225

226
    /**
227
     * Exits if the minimum requirements of PHP_CodeSniffer are not met.
228
     *
229
     * @return void
230
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the requirements are not met.
231
     */
232
    public function checkRequirements()
×
233
    {
234
        // Check the PHP version.
235
        if (PHP_VERSION_ID < 70200) {
×
236
            $error = 'ERROR: PHP_CodeSniffer requires PHP version 7.2.0 or greater.'.PHP_EOL;
×
237
            throw new DeepExitException($error, 3);
×
238
        }
239

240
        $requiredExtensions = [
×
241
            'tokenizer',
×
242
            'xmlwriter',
×
243
            'SimpleXML',
×
244
        ];
×
245
        $missingExtensions  = [];
×
246

247
        foreach ($requiredExtensions as $extension) {
×
248
            if (extension_loaded($extension) === false) {
×
249
                $missingExtensions[] = $extension;
×
250
            }
251
        }
252

253
        if (empty($missingExtensions) === false) {
×
254
            $last      = array_pop($requiredExtensions);
×
255
            $required  = implode(', ', $requiredExtensions);
×
256
            $required .= ' and '.$last;
×
257

258
            if (count($missingExtensions) === 1) {
×
259
                $missing = $missingExtensions[0];
×
260
            } else {
261
                $last     = array_pop($missingExtensions);
×
262
                $missing  = implode(', ', $missingExtensions);
×
263
                $missing .= ' and '.$last;
×
264
            }
265

266
            $error = 'ERROR: PHP_CodeSniffer requires the %s extensions to be enabled. Please enable %s.'.PHP_EOL;
×
267
            $error = sprintf($error, $required, $missing);
×
268
            throw new DeepExitException($error, 3);
×
269
        }
270

271
    }//end checkRequirements()
272

273

274
    /**
275
     * Init the rulesets and other high-level settings.
276
     *
277
     * @return void
278
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If a referenced standard is not installed.
279
     */
280
    public function init()
×
281
    {
282
        if (defined('PHP_CODESNIFFER_CBF') === false) {
×
283
            define('PHP_CODESNIFFER_CBF', false);
×
284
        }
285

286
        // Disable the PCRE JIT as this caused issues with parallel running.
287
        ini_set('pcre.jit', false);
×
288

289
        // Check that the standards are valid.
290
        foreach ($this->config->standards as $standard) {
×
291
            if (Util\Standards::isInstalledStandard($standard) === false) {
×
292
                // They didn't select a valid coding standard, so help them
293
                // out by letting them know which standards are installed.
294
                $error = 'ERROR: the "'.$standard.'" coding standard is not installed. ';
×
295
                ob_start();
×
296
                Util\Standards::printInstalledStandards();
×
297
                $error .= ob_get_contents();
×
298
                ob_end_clean();
×
299
                throw new DeepExitException($error, 3);
×
300
            }
301
        }
302

303
        // Saves passing the Config object into other objects that only need
304
        // the verbosity flag for debug output.
305
        if (defined('PHP_CODESNIFFER_VERBOSITY') === false) {
×
306
            define('PHP_CODESNIFFER_VERBOSITY', $this->config->verbosity);
×
307
        }
308

309
        // Create this class so it is autoloaded and sets up a bunch
310
        // of PHP_CodeSniffer-specific token type constants.
311
        $tokens = new Util\Tokens();
×
312

313
        // Allow autoloading of custom files inside installed standards.
314
        $installedStandards = Standards::getInstalledStandardDetails();
×
315
        foreach ($installedStandards as $name => $details) {
×
316
            Autoload::addSearchPath($details['path'], $details['namespace']);
×
317
        }
318

319
        // The ruleset contains all the information about how the files
320
        // should be checked and/or fixed.
321
        try {
322
            $this->ruleset = new Ruleset($this->config);
×
323
        } catch (RuntimeException $e) {
×
324
            $error  = 'ERROR: '.$e->getMessage().PHP_EOL.PHP_EOL;
×
325
            $error .= $this->config->printShortUsage(true);
×
326
            throw new DeepExitException($error, 3);
×
327
        }
328

329
    }//end init()
330

331

332
    /**
333
     * Performs the run.
334
     *
335
     * @return int The number of errors and warnings found.
336
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
337
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException
338
     */
339
    private function run()
×
340
    {
341
        // The class that manages all reporters for the run.
342
        $this->reporter = new Reporter($this->config);
×
343

344
        // Include bootstrap files.
345
        foreach ($this->config->bootstrap as $bootstrap) {
×
346
            include $bootstrap;
×
347
        }
348

349
        if ($this->config->stdin === true) {
×
350
            $fileContents = $this->config->stdinContent;
×
351
            if ($fileContents === null) {
×
352
                $handle = fopen('php://stdin', 'r');
×
353
                stream_set_blocking($handle, true);
×
354
                $fileContents = stream_get_contents($handle);
×
355
                fclose($handle);
×
356
            }
357

358
            $todo  = new FileList($this->config, $this->ruleset);
×
359
            $dummy = new DummyFile($fileContents, $this->ruleset, $this->config);
×
360
            $todo->addFile($dummy->path, $dummy);
×
361
        } else {
362
            if (empty($this->config->files) === true) {
×
363
                $error  = 'ERROR: You must supply at least one file or directory to process.'.PHP_EOL.PHP_EOL;
×
364
                $error .= $this->config->printShortUsage(true);
×
365
                throw new DeepExitException($error, 3);
×
366
            }
367

368
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
369
                Common::printStatusMessage('Creating file list... ', 0, true);
×
370
            }
371

372
            $todo = new FileList($this->config, $this->ruleset);
×
373

374
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
375
                $numFiles = count($todo);
×
376
                Common::printStatusMessage("DONE ($numFiles files in queue)");
×
377
            }
378

379
            if ($this->config->cache === true) {
×
380
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
381
                    Common::printStatusMessage('Loading cache... ', 0, true);
×
382
                }
383

384
                Cache::load($this->ruleset, $this->config);
×
385

386
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
387
                    $size = Cache::getSize();
×
388
                    Common::printStatusMessage("DONE ($size files in cache)");
×
389
                }
390
            }
391
        }//end if
392

393
        $numFiles = count($todo);
×
394
        if ($numFiles === 0) {
×
395
            $error  = 'ERROR: No files were checked'.PHP_EOL;
×
396
            $error .= 'All specified files were excluded or did not match filtering rules'.PHP_EOL.PHP_EOL;
×
397
            throw new DeepExitException($error, 3);
×
398
        }
399

400
        // Turn all sniff errors into exceptions.
401
        set_error_handler([$this, 'handleErrors']);
×
402

403
        // If verbosity is too high, turn off parallelism so the
404
        // debug output is clean.
405
        if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
406
            $this->config->parallel = 1;
×
407
        }
408

409
        // If the PCNTL extension isn't installed, we can't fork.
410
        if (function_exists('pcntl_fork') === false) {
×
411
            $this->config->parallel = 1;
×
412
        }
413

414
        $lastDir = '';
×
415

416
        if ($this->config->parallel === 1) {
×
417
            // Running normally.
418
            $numProcessed = 0;
×
419
            foreach ($todo as $path => $file) {
×
420
                if ($file->ignored === false) {
×
421
                    $currDir = dirname($path);
×
422
                    if ($lastDir !== $currDir) {
×
423
                        if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
424
                            Common::printStatusMessage('Changing into directory '.Common::stripBasepath($currDir, $this->config->basepath));
×
425
                        }
426

427
                        $lastDir = $currDir;
×
428
                    }
429

430
                    $this->processFile($file);
×
431
                } else if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
432
                    Common::printStatusMessage('Skipping '.basename($file->path));
×
433
                }
434

435
                $numProcessed++;
×
436
                $this->printProgress($file, $numFiles, $numProcessed);
×
437
            }
438
        } else {
439
            // Batching and forking.
440
            $childProcs  = [];
×
441
            $numPerBatch = ceil($numFiles / $this->config->parallel);
×
442

443
            for ($batch = 0; $batch < $this->config->parallel; $batch++) {
×
444
                $startAt = ($batch * $numPerBatch);
×
445
                if ($startAt >= $numFiles) {
×
446
                    break;
×
447
                }
448

449
                $endAt = ($startAt + $numPerBatch);
×
450
                if ($endAt > $numFiles) {
×
451
                    $endAt = $numFiles;
×
452
                }
453

454
                $childOutFilename = tempnam(sys_get_temp_dir(), 'phpcs-child');
×
455
                $pid = pcntl_fork();
×
456
                if ($pid === -1) {
×
457
                    throw new RuntimeException('Failed to create child process');
×
458
                } else if ($pid !== 0) {
×
459
                    $childProcs[$pid] = $childOutFilename;
×
460
                } else {
461
                    // Move forward to the start of the batch.
462
                    $todo->rewind();
×
463
                    for ($i = 0; $i < $startAt; $i++) {
×
464
                        $todo->next();
×
465
                    }
466

467
                    // Reset the reporter to make sure only figures from this
468
                    // file batch are recorded.
469
                    $this->reporter->totalFiles    = 0;
×
470
                    $this->reporter->totalErrors   = 0;
×
471
                    $this->reporter->totalWarnings = 0;
×
472
                    $this->reporter->totalFixable  = 0;
×
473
                    $this->reporter->totalFixed    = 0;
×
474

475
                    // Process the files.
476
                    $pathsProcessed = [];
×
477
                    ob_start();
×
478
                    for ($i = $startAt; $i < $endAt; $i++) {
×
479
                        $path = $todo->key();
×
480
                        $file = $todo->current();
×
481

482
                        if ($file->ignored === true) {
×
483
                            $todo->next();
×
484
                            continue;
×
485
                        }
486

487
                        $currDir = dirname($path);
×
488
                        if ($lastDir !== $currDir) {
×
489
                            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
490
                                Common::printStatusMessage('Changing into directory '.Common::stripBasepath($currDir, $this->config->basepath));
×
491
                            }
492

493
                            $lastDir = $currDir;
×
494
                        }
495

496
                        $this->processFile($file);
×
497

498
                        $pathsProcessed[] = $path;
×
499
                        $todo->next();
×
500
                    }//end for
501

502
                    $debugOutput = ob_get_contents();
×
503
                    ob_end_clean();
×
504

505
                    // Write information about the run to the filesystem
506
                    // so it can be picked up by the main process.
507
                    $childOutput = [
×
508
                        'totalFiles'    => $this->reporter->totalFiles,
×
509
                        'totalErrors'   => $this->reporter->totalErrors,
×
510
                        'totalWarnings' => $this->reporter->totalWarnings,
×
511
                        'totalFixable'  => $this->reporter->totalFixable,
×
512
                        'totalFixed'    => $this->reporter->totalFixed,
×
513
                    ];
×
514

515
                    $output  = '<'.'?php'."\n".' $childOutput = ';
×
516
                    $output .= var_export($childOutput, true);
×
517
                    $output .= ";\n\$debugOutput = ";
×
518
                    $output .= var_export($debugOutput, true);
×
519

520
                    if ($this->config->cache === true) {
×
521
                        $childCache = [];
×
522
                        foreach ($pathsProcessed as $path) {
×
523
                            $childCache[$path] = Cache::get($path);
×
524
                        }
525

526
                        $output .= ";\n\$childCache = ";
×
527
                        $output .= var_export($childCache, true);
×
528
                    }
529

530
                    $output .= ";\n?".'>';
×
531
                    file_put_contents($childOutFilename, $output);
×
532
                    exit();
×
533
                }//end if
534
            }//end for
535

536
            $success = $this->processChildProcs($childProcs);
×
537
            if ($success === false) {
×
538
                throw new RuntimeException('One or more child processes failed to run');
×
539
            }
540
        }//end if
541

542
        restore_error_handler();
×
543

544
        if (PHP_CODESNIFFER_VERBOSITY === 0
×
545
            && $this->config->interactive === false
×
546
            && $this->config->showProgress === true
×
547
        ) {
548
            Common::printStatusMessage(PHP_EOL, 0, true);
×
549
        }
550

551
        if ($this->config->cache === true) {
×
552
            Cache::save();
×
553
        }
554

555
        $ignoreWarnings = Config::getConfigData('ignore_warnings_on_exit');
×
556
        $ignoreErrors   = Config::getConfigData('ignore_errors_on_exit');
×
557

558
        $return = ($this->reporter->totalErrors + $this->reporter->totalWarnings);
×
559
        if ($ignoreErrors !== null) {
×
560
            $ignoreErrors = (bool) $ignoreErrors;
×
561
            if ($ignoreErrors === true) {
×
562
                $return -= $this->reporter->totalErrors;
×
563
            }
564
        }
565

566
        if ($ignoreWarnings !== null) {
×
567
            $ignoreWarnings = (bool) $ignoreWarnings;
×
568
            if ($ignoreWarnings === true) {
×
569
                $return -= $this->reporter->totalWarnings;
×
570
            }
571
        }
572

573
        return $return;
×
574

575
    }//end run()
576

577

578
    /**
579
     * Converts all PHP errors into exceptions.
580
     *
581
     * This method forces a sniff to stop processing if it is not
582
     * able to handle a specific piece of code, instead of continuing
583
     * and potentially getting into a loop.
584
     *
585
     * @param int    $code    The level of error raised.
586
     * @param string $message The error message.
587
     * @param string $file    The path of the file that raised the error.
588
     * @param int    $line    The line number the error was raised at.
589
     *
590
     * @return bool
591
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException
592
     */
593
    public function handleErrors($code, $message, $file, $line)
×
594
    {
595
        if ((error_reporting() & $code) === 0) {
×
596
            // This type of error is being muted.
597
            return true;
×
598
        }
599

600
        throw new RuntimeException("$message in $file on line $line");
×
601

602
    }//end handleErrors()
603

604

605
    /**
606
     * Processes a single file, including checking and fixing.
607
     *
608
     * @param \PHP_CodeSniffer\Files\File $file The file to be processed.
609
     *
610
     * @return void
611
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
612
     */
613
    public function processFile($file)
×
614
    {
615
        if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
616
            $startTime = microtime(true);
×
617
            Common::printStatusMessage('Processing '.basename($file->path).' ', 0, true);
×
618
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
619
                Common::printStatusMessage(PHP_EOL, 0, true);
×
620
            }
621
        }
622

623
        try {
624
            $file->process();
×
625

626
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
627
                $timeTaken = ((microtime(true) - $startTime) * 1000);
×
628
                if ($timeTaken < 1000) {
×
629
                    $timeTaken = round($timeTaken);
×
630
                    Common::printStatusMessage("DONE in {$timeTaken}ms", 0, true);
×
631
                } else {
632
                    $timeTaken = round(($timeTaken / 1000), 2);
×
633
                    Common::printStatusMessage("DONE in $timeTaken secs", 0, true);
×
634
                }
635

636
                if (PHP_CODESNIFFER_CBF === true) {
×
637
                    $errors = $file->getFixableCount();
×
638
                    Common::printStatusMessage(" ($errors fixable violations)");
×
639
                } else {
640
                    $errors   = $file->getErrorCount();
×
641
                    $warnings = $file->getWarningCount();
×
642
                    Common::printStatusMessage(" ($errors errors, $warnings warnings)");
×
643
                }
644
            }
645
        } catch (\Exception $e) {
×
646
            $error = 'An error occurred during processing; checking has been aborted. The error message was: '.$e->getMessage();
×
647

648
            // Determine which sniff caused the error.
649
            $sniffStack = null;
×
650
            $nextStack  = null;
×
651
            foreach ($e->getTrace() as $step) {
×
652
                if (isset($step['file']) === false) {
×
653
                    continue;
×
654
                }
655

656
                if (empty($sniffStack) === false) {
×
657
                    $nextStack = $step;
×
658
                    break;
×
659
                }
660

661
                if (substr($step['file'], -9) === 'Sniff.php') {
×
662
                    $sniffStack = $step;
×
663
                    continue;
×
664
                }
665
            }
666

667
            if (empty($sniffStack) === false) {
×
668
                if (empty($nextStack) === false
×
669
                    && isset($nextStack['class']) === true
×
670
                    && substr($nextStack['class'], -5) === 'Sniff'
×
671
                ) {
672
                    $sniffCode = Common::getSniffCode($nextStack['class']);
×
673
                } else {
674
                    $sniffCode = substr(strrchr(str_replace('\\', '/', $sniffStack['file']), '/'), 1);
×
675
                }
676

677
                $error .= sprintf(PHP_EOL.'The error originated in the %s sniff on line %s.', $sniffCode, $sniffStack['line']);
×
678
            }
679

680
            $file->addErrorOnLine($error, 1, 'Internal.Exception');
×
681
        }//end try
682

NEW
683
        $this->reporter->cacheFileReport($file);
×
684

685
        if ($this->config->interactive === true) {
×
686
            /*
687
                Running interactively.
688
                Print the error report for the current file and then wait for user input.
689
            */
690

691
            // Get current violations and then clear the list to make sure
692
            // we only print violations for a single file each time.
693
            $numErrors = null;
×
694
            while ($numErrors !== 0) {
×
695
                $numErrors = ($file->getErrorCount() + $file->getWarningCount());
×
696
                if ($numErrors === 0) {
×
697
                    continue;
×
698
                }
699

700
                $this->reporter->printReport('full');
×
701

702
                echo '<ENTER> to recheck, [s] to skip or [q] to quit : ';
×
703
                $input = fgets(STDIN);
×
704
                $input = trim($input);
×
705

706
                switch ($input) {
707
                case 's':
×
708
                    break(2);
×
709
                case 'q':
×
710
                    throw new DeepExitException('', 0);
×
711
                default:
712
                    // Repopulate the sniffs because some of them save their state
713
                    // and only clear it when the file changes, but we are rechecking
714
                    // the same file.
715
                    $file->ruleset->populateTokenListeners();
×
716
                    $file->reloadContent();
×
717
                    $file->process();
×
NEW
718
                    $this->reporter->cacheFileReport($file);
×
719
                    break;
×
720
                }
721
            }//end while
722
        }//end if
723

724
        // Clean up the file to save (a lot of) memory.
725
        $file->cleanUp();
×
726

727
    }//end processFile()
728

729

730
    /**
731
     * Waits for child processes to complete and cleans up after them.
732
     *
733
     * The reporting information returned by each child process is merged
734
     * into the main reporter class.
735
     *
736
     * @param array $childProcs An array of child processes to wait for.
737
     *
738
     * @return bool
739
     */
740
    private function processChildProcs($childProcs)
×
741
    {
742
        $numProcessed = 0;
×
743
        $totalBatches = count($childProcs);
×
744

745
        $success = true;
×
746

747
        while (count($childProcs) > 0) {
×
748
            $pid = pcntl_waitpid(0, $status);
×
749
            if ($pid <= 0) {
×
750
                continue;
×
751
            }
752

753
            $childProcessStatus = pcntl_wexitstatus($status);
×
754
            if ($childProcessStatus !== 0) {
×
755
                $success = false;
×
756
            }
757

758
            $out = $childProcs[$pid];
×
759
            unset($childProcs[$pid]);
×
760
            if (file_exists($out) === false) {
×
761
                continue;
×
762
            }
763

764
            include $out;
×
765
            unlink($out);
×
766

767
            $numProcessed++;
×
768

769
            if (isset($childOutput) === false) {
×
770
                // The child process died, so the run has failed.
771
                $file = new DummyFile('', $this->ruleset, $this->config);
×
772
                $file->setErrorCounts(1, 0, 0, 0);
×
773
                $this->printProgress($file, $totalBatches, $numProcessed);
×
774
                $success = false;
×
775
                continue;
×
776
            }
777

778
            $this->reporter->totalFiles    += $childOutput['totalFiles'];
×
779
            $this->reporter->totalErrors   += $childOutput['totalErrors'];
×
780
            $this->reporter->totalWarnings += $childOutput['totalWarnings'];
×
781
            $this->reporter->totalFixable  += $childOutput['totalFixable'];
×
782
            $this->reporter->totalFixed    += $childOutput['totalFixed'];
×
783

784
            if (isset($debugOutput) === true) {
×
785
                echo $debugOutput;
×
786
            }
787

788
            if (isset($childCache) === true) {
×
789
                foreach ($childCache as $path => $cache) {
×
790
                    Cache::set($path, $cache);
×
791
                }
792
            }
793

794
            // Fake a processed file so we can print progress output for the batch.
795
            $file = new DummyFile('', $this->ruleset, $this->config);
×
796
            $file->setErrorCounts(
×
797
                $childOutput['totalErrors'],
×
798
                $childOutput['totalWarnings'],
×
799
                $childOutput['totalFixable'],
×
800
                $childOutput['totalFixed']
×
801
            );
×
802
            $this->printProgress($file, $totalBatches, $numProcessed);
×
803
        }//end while
804

805
        return $success;
×
806

807
    }//end processChildProcs()
808

809

810
    /**
811
     * Print progress information for a single processed file.
812
     *
813
     * @param \PHP_CodeSniffer\Files\File $file         The file that was processed.
814
     * @param int                         $numFiles     The total number of files to process.
815
     * @param int                         $numProcessed The number of files that have been processed,
816
     *                                                  including this one.
817
     *
818
     * @return void
819
     */
820
    public function printProgress(File $file, $numFiles, $numProcessed)
×
821
    {
822
        if (PHP_CODESNIFFER_VERBOSITY > 0
×
823
            || $this->config->showProgress === false
×
824
        ) {
825
            return;
×
826
        }
827

828
        // Show progress information.
829
        if ($file->ignored === true) {
×
830
            Common::printStatusMessage('S', 0, true);
×
831
        } else {
832
            $errors   = $file->getErrorCount();
×
833
            $warnings = $file->getWarningCount();
×
834
            $fixable  = $file->getFixableCount();
×
835
            $fixed    = $file->getFixedCount();
×
836

837
            if (PHP_CODESNIFFER_CBF === true) {
×
838
                // Files with fixed errors or warnings are F (green).
839
                // Files with unfixable errors or warnings are E (red).
840
                // Files with no errors or warnings are . (black).
841
                if ($fixable > 0) {
×
842
                    if ($this->config->colors === true) {
×
843
                        Common::printStatusMessage("\033[31m", 0, true);
×
844
                    }
845

846
                    Common::printStatusMessage('E', 0, true);
×
847

848
                    if ($this->config->colors === true) {
×
849
                        Common::printStatusMessage("\033[0m", 0, true);
×
850
                    }
851
                } else if ($fixed > 0) {
×
852
                    if ($this->config->colors === true) {
×
853
                        Common::printStatusMessage("\033[32m", 0, true);
×
854
                    }
855

856
                    Common::printStatusMessage('F', 0, true);
×
857

858
                    if ($this->config->colors === true) {
×
859
                        Common::printStatusMessage("\033[0m", 0, true);
×
860
                    }
861
                } else {
862
                    Common::printStatusMessage('.', 0, true);
×
863
                }//end if
864
            } else {
865
                // Files with errors are E (red).
866
                // Files with fixable errors are E (green).
867
                // Files with warnings are W (yellow).
868
                // Files with fixable warnings are W (green).
869
                // Files with no errors or warnings are . (black).
870
                if ($errors > 0) {
×
871
                    if ($this->config->colors === true) {
×
872
                        if ($fixable > 0) {
×
873
                            Common::printStatusMessage("\033[32m", 0, true);
×
874
                        } else {
875
                            Common::printStatusMessage("\033[31m", 0, true);
×
876
                        }
877
                    }
878

879
                    Common::printStatusMessage('E', 0, true);
×
880

881
                    if ($this->config->colors === true) {
×
882
                        Common::printStatusMessage("\033[0m", 0, true);
×
883
                    }
884
                } else if ($warnings > 0) {
×
885
                    if ($this->config->colors === true) {
×
886
                        if ($fixable > 0) {
×
887
                            Common::printStatusMessage("\033[32m", 0, true);
×
888
                        } else {
889
                            Common::printStatusMessage("\033[33m", 0, true);
×
890
                        }
891
                    }
892

893
                    Common::printStatusMessage('W', 0, true);
×
894

895
                    if ($this->config->colors === true) {
×
896
                        Common::printStatusMessage("\033[0m", 0, true);
×
897
                    }
898
                } else {
899
                    Common::printStatusMessage('.', 0, true);
×
900
                }//end if
901
            }//end if
902
        }//end if
903

904
        $numPerLine = 60;
×
905
        if ($numProcessed !== $numFiles && ($numProcessed % $numPerLine) !== 0) {
×
906
            return;
×
907
        }
908

909
        $percent = round(($numProcessed / $numFiles) * 100);
×
910
        $padding = (strlen($numFiles) - strlen($numProcessed));
×
911
        if ($numProcessed === $numFiles
×
912
            && $numFiles > $numPerLine
×
913
            && ($numProcessed % $numPerLine) !== 0
×
914
        ) {
915
            $padding += ($numPerLine - ($numFiles - (floor($numFiles / $numPerLine) * $numPerLine)));
×
916
        }
917

918
        Common::printStatusMessage(str_repeat(' ', $padding)." $numProcessed / $numFiles ($percent%)");
×
919

920
    }//end printProgress()
921

922

923
    /**
924
     * Registers a PHP shutdown function to provide a more informative out of memory error.
925
     *
926
     * @param string $command The command which was used to initiate the PHPCS run.
927
     *
928
     * @return void
929
     */
930
    private function registerOutOfMemoryShutdownMessage($command)
×
931
    {
932
        // Allocate all needed memory beforehand as much as possible.
933
        $errorMsg    = PHP_EOL.'The PHP_CodeSniffer "%1$s" command ran out of memory.'.PHP_EOL;
×
934
        $errorMsg   .= 'Either raise the "memory_limit" of PHP in the php.ini file or raise the memory limit at runtime'.PHP_EOL;
×
935
        $errorMsg   .= 'using `%1$s -d memory_limit=512M` (replace 512M with the desired memory limit).'.PHP_EOL;
×
936
        $errorMsg    = sprintf($errorMsg, $command);
×
937
        $memoryError = 'Allowed memory size of';
×
938
        $errorArray  = [
×
939
            'type'    => 42,
×
940
            'message' => 'Some random dummy string to take up memory and take up some more memory and some more',
×
941
            'file'    => 'Another random string, which would be a filename this time. Should be relatively long to allow for deeply nested files',
×
942
            'line'    => 31427,
×
943
        ];
×
944

945
        register_shutdown_function(
×
946
            static function () use (
947
                $errorMsg,
×
948
                $memoryError,
×
949
                $errorArray
×
950
            ) {
×
951
                $errorArray = error_get_last();
×
952
                if (is_array($errorArray) === true && strpos($errorArray['message'], $memoryError) !== false) {
×
953
                    echo $errorMsg;
×
954
                }
955
            }
×
956
        );
×
957

958
    }//end registerOutOfMemoryShutdownMessage()
959

960

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