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

PHPCSStandards / PHP_CodeSniffer / 14732455750

29 Apr 2025 01:27PM UTC coverage: 78.302% (+0.007%) from 78.295%
14732455750

Pull #1054

github

web-flow
Merge 4b912a7d0 into d12e243d8
Pull Request #1054: Standards: introduce `prepareInstalledStandardsForDisplay()` method

0 of 11 new or added lines in 3 files covered. (0.0%)

1 existing line in 1 file now uncovered.

19548 of 24965 relevant lines covered (78.3%)

86.08 hits per line

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

20.91
/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
            echo $e->getMessage();
×
130
            return $e->getCode();
×
131
        }//end try
132

133
        if ($numErrors === 0) {
×
134
            // No errors found.
135
            return 0;
×
136
        } else if ($this->reporter->totalFixable === 0) {
×
137
            // Errors found, but none of them can be fixed by PHPCBF.
138
            return 1;
×
139
        } else {
140
            // Errors found, and some can be fixed by PHPCBF.
141
            return 2;
×
142
        }
143

144
    }//end runPHPCS()
145

146

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

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

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

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

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

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

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

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

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

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

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

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

210
            if ($this->config->quiet === false) {
×
211
                StatusWriter::writeNewline();
×
212
                Timing::printRunTime();
×
213
            }
214
        } catch (DeepExitException $e) {
×
215
            echo $e->getMessage();
×
216
            return $e->getCode();
×
217
        }//end try
218

219
        if ($this->reporter->totalFixed === 0) {
×
220
            // Nothing was fixed by PHPCBF.
221
            if ($this->reporter->totalFixable === 0) {
×
222
                // Nothing found that could be fixed.
223
                return 0;
×
224
            } else {
225
                // Something failed to fix.
226
                return 2;
×
227
            }
228
        }
229

230
        if ($this->reporter->totalFixable === 0) {
×
231
            // PHPCBF fixed all fixable errors.
232
            return 1;
×
233
        }
234

235
        // PHPCBF fixed some fixable errors, but others failed to fix.
236
        return 2;
×
237

238
    }//end runPHPCBF()
239

240

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

253
        // Disable the PCRE JIT as this caused issues with parallel running.
254
        ini_set('pcre.jit', false);
×
255

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

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

273
        // Create this class so it is autoloaded and sets up a bunch
274
        // of PHP_CodeSniffer-specific token type constants.
275
        new Tokens();
×
276

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

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

288
            if ($this->ruleset->hasSniffDeprecations() === true) {
×
289
                $this->ruleset->showSniffDeprecations();
×
290
            }
291
        } catch (RuntimeException $e) {
×
292
            $error  = rtrim($e->getMessage(), "\r\n").PHP_EOL.PHP_EOL;
×
293
            $error .= $this->config->printShortUsage(true);
×
294
            throw new DeepExitException($error, 3);
×
295
        }
296

297
    }//end init()
298

299

300
    /**
301
     * Performs the run.
302
     *
303
     * @return int The number of errors and warnings found.
304
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
305
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException
306
     */
307
    private function run()
12✔
308
    {
309
        // The class that manages all reporters for the run.
310
        $this->reporter = new Reporter($this->config);
12✔
311

312
        // Include bootstrap files.
313
        foreach ($this->config->bootstrap as $bootstrap) {
12✔
314
            include $bootstrap;
×
315
        }
316

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

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

336
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
12✔
337
                StatusWriter::write('Creating file list... ', 0, 0);
×
338
            }
339

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

342
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
12✔
343
                $numFiles = count($todo);
×
344
                StatusWriter::write("DONE ($numFiles files in queue)");
×
345
            }
346

347
            if ($this->config->cache === true) {
12✔
348
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
349
                    StatusWriter::write('Loading cache... ', 0, 0);
×
350
                }
351

352
                Cache::load($this->ruleset, $this->config);
×
353

354
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
355
                    $size = Cache::getSize();
×
356
                    StatusWriter::write("DONE ($size files in cache)");
×
357
                }
358
            }
359
        }//end if
360

361
        $numFiles = count($todo);
12✔
362
        if ($numFiles === 0) {
12✔
363
            $error  = 'ERROR: No files were checked.'.PHP_EOL;
12✔
364
            $error .= 'All specified files were excluded or did not match filtering rules.'.PHP_EOL.PHP_EOL;
12✔
365
            throw new DeepExitException($error, 3);
12✔
366
        }
367

368
        // Turn all sniff errors into exceptions.
369
        set_error_handler([$this, 'handleErrors']);
×
370

371
        // If verbosity is too high, turn off parallelism so the
372
        // debug output is clean.
373
        if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
374
            $this->config->parallel = 1;
×
375
        }
376

377
        // If the PCNTL extension isn't installed, we can't fork.
378
        if (function_exists('pcntl_fork') === false) {
×
379
            $this->config->parallel = 1;
×
380
        }
381

382
        $lastDir = '';
×
383

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

395
                        $lastDir = $currDir;
×
396
                    }
397

398
                    $this->processFile($file);
×
399
                } else if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
400
                    StatusWriter::write('Skipping '.basename($file->path));
×
401
                }
402

403
                $numProcessed++;
×
404
                $this->printProgress($file, $numFiles, $numProcessed);
×
405
            }
406
        } else {
407
            // Batching and forking.
408
            $childProcs  = [];
×
409
            $numPerBatch = ceil($numFiles / $this->config->parallel);
×
410

411
            for ($batch = 0; $batch < $this->config->parallel; $batch++) {
×
412
                $startAt = ($batch * $numPerBatch);
×
413
                if ($startAt >= $numFiles) {
×
414
                    break;
×
415
                }
416

417
                $endAt = ($startAt + $numPerBatch);
×
418
                if ($endAt > $numFiles) {
×
419
                    $endAt = $numFiles;
×
420
                }
421

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

435
                    // Reset the reporter to make sure only figures from this
436
                    // file batch are recorded.
437
                    $this->reporter->totalFiles    = 0;
×
438
                    $this->reporter->totalErrors   = 0;
×
439
                    $this->reporter->totalWarnings = 0;
×
440
                    $this->reporter->totalFixable  = 0;
×
441
                    $this->reporter->totalFixed    = 0;
×
442

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

450
                        if ($file->ignored === true) {
×
451
                            $todo->next();
×
452
                            continue;
×
453
                        }
454

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

461
                            $lastDir = $currDir;
×
462
                        }
463

464
                        $this->processFile($file);
×
465

466
                        $pathsProcessed[] = $path;
×
467
                        $todo->next();
×
468
                    }//end for
469

470
                    $debugOutput = ob_get_contents();
×
471
                    ob_end_clean();
×
472

473
                    // Write information about the run to the filesystem
474
                    // so it can be picked up by the main process.
475
                    $childOutput = [
476
                        'totalFiles'    => $this->reporter->totalFiles,
×
477
                        'totalErrors'   => $this->reporter->totalErrors,
×
478
                        'totalWarnings' => $this->reporter->totalWarnings,
×
479
                        'totalFixable'  => $this->reporter->totalFixable,
×
480
                        'totalFixed'    => $this->reporter->totalFixed,
×
481
                    ];
482

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

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

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

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

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

510
        restore_error_handler();
×
511

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

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

523
        $ignoreWarnings = Config::getConfigData('ignore_warnings_on_exit');
×
524
        $ignoreErrors   = Config::getConfigData('ignore_errors_on_exit');
×
525

526
        $return = ($this->reporter->totalErrors + $this->reporter->totalWarnings);
×
527
        if ($ignoreErrors !== null) {
×
528
            $ignoreErrors = (bool) $ignoreErrors;
×
529
            if ($ignoreErrors === true) {
×
530
                $return -= $this->reporter->totalErrors;
×
531
            }
532
        }
533

534
        if ($ignoreWarnings !== null) {
×
535
            $ignoreWarnings = (bool) $ignoreWarnings;
×
536
            if ($ignoreWarnings === true) {
×
537
                $return -= $this->reporter->totalWarnings;
×
538
            }
539
        }
540

541
        return $return;
×
542

543
    }//end run()
544

545

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

568
        throw new RuntimeException("$message in $file on line $line");
×
569

570
    }//end handleErrors()
571

572

573
    /**
574
     * Processes a single file, including checking and fixing.
575
     *
576
     * @param \PHP_CodeSniffer\Files\File $file The file to be processed.
577
     *
578
     * @return void
579
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
580
     */
581
    public function processFile($file)
×
582
    {
583
        if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
584
            $startTime = microtime(true);
×
585
            $newlines  = 0;
×
586
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
587
                $newlines = 1;
×
588
            }
589

590
            StatusWriter::write('Processing '.basename($file->path).' ', 0, $newlines);
×
591
        }
592

593
        try {
594
            $file->process();
×
595

596
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
597
                $timeTaken = ((microtime(true) - $startTime) * 1000);
×
598
                if ($timeTaken < 1000) {
×
599
                    $timeTaken = round($timeTaken);
×
600
                    StatusWriter::write("DONE in {$timeTaken}ms", 0, 0);
×
601
                } else {
602
                    $timeTaken = round(($timeTaken / 1000), 2);
×
603
                    StatusWriter::write("DONE in $timeTaken secs", 0, 0);
×
604
                }
605

606
                if (PHP_CODESNIFFER_CBF === true) {
×
607
                    $errors = $file->getFixableCount();
×
608
                    StatusWriter::write(" ($errors fixable violations)");
×
609
                } else {
610
                    $errors   = $file->getErrorCount();
×
611
                    $warnings = $file->getWarningCount();
×
612
                    StatusWriter::write(" ($errors errors, $warnings warnings)");
×
613
                }
614
            }
615
        } catch (Exception $e) {
×
616
            $error = 'An error occurred during processing; checking has been aborted. The error message was: '.$e->getMessage();
×
617

618
            // Determine which sniff caused the error.
619
            $sniffStack = null;
×
620
            $nextStack  = null;
×
621
            foreach ($e->getTrace() as $step) {
×
622
                if (isset($step['file']) === false) {
×
623
                    continue;
×
624
                }
625

626
                if (empty($sniffStack) === false) {
×
627
                    $nextStack = $step;
×
628
                    break;
×
629
                }
630

631
                if (substr($step['file'], -9) === 'Sniff.php') {
×
632
                    $sniffStack = $step;
×
633
                    continue;
×
634
                }
635
            }
636

637
            if (empty($sniffStack) === false) {
×
638
                $sniffCode = '';
×
639
                try {
640
                    if (empty($nextStack) === false
×
641
                        && isset($nextStack['class']) === true
×
642
                    ) {
643
                        $sniffCode = 'the '.Common::getSniffCode($nextStack['class']).' sniff';
×
644
                    }
645
                } catch (InvalidArgumentException $e) {
×
646
                    // Sniff code could not be determined. This may be an abstract sniff class.
647
                }
648

649
                if ($sniffCode === '') {
×
650
                    $sniffCode = substr(strrchr(str_replace('\\', '/', $sniffStack['file']), '/'), 1);
×
651
                }
652

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

656
            $file->addErrorOnLine($error, 1, 'Internal.Exception');
×
657
        }//end try
658

659
        $this->reporter->cacheFileReport($file);
×
660

661
        if ($this->config->interactive === true) {
×
662
            /*
663
                Running interactively.
664
                Print the error report for the current file and then wait for user input.
665
            */
666

667
            // Get current violations and then clear the list to make sure
668
            // we only print violations for a single file each time.
669
            $numErrors = null;
×
670
            while ($numErrors !== 0) {
×
671
                $numErrors = ($file->getErrorCount() + $file->getWarningCount());
×
672
                if ($numErrors === 0) {
×
673
                    continue;
×
674
                }
675

676
                $this->reporter->printReport('full');
×
677

678
                echo '<ENTER> to recheck, [s] to skip or [q] to quit : ';
×
679
                $input = fgets(STDIN);
×
680
                $input = trim($input);
×
681

682
                switch ($input) {
683
                case 's':
×
684
                    break(2);
×
685
                case 'q':
×
686
                    throw new DeepExitException('', 0);
×
687
                default:
688
                    // Repopulate the sniffs because some of them save their state
689
                    // and only clear it when the file changes, but we are rechecking
690
                    // the same file.
691
                    $file->ruleset->populateTokenListeners();
×
692
                    $file->reloadContent();
×
693
                    $file->process();
×
694
                    $this->reporter->cacheFileReport($file);
×
695
                    break;
×
696
                }
697
            }//end while
698
        }//end if
699

700
        // Clean up the file to save (a lot of) memory.
701
        $file->cleanUp();
×
702

703
    }//end processFile()
704

705

706
    /**
707
     * Waits for child processes to complete and cleans up after them.
708
     *
709
     * The reporting information returned by each child process is merged
710
     * into the main reporter class.
711
     *
712
     * @param array $childProcs An array of child processes to wait for.
713
     *
714
     * @return bool
715
     */
716
    private function processChildProcs($childProcs)
×
717
    {
718
        $numProcessed = 0;
×
719
        $totalBatches = count($childProcs);
×
720

721
        $success = true;
×
722

723
        while (count($childProcs) > 0) {
×
724
            $pid = pcntl_waitpid(0, $status);
×
725
            if ($pid <= 0) {
×
726
                continue;
×
727
            }
728

729
            $childProcessStatus = pcntl_wexitstatus($status);
×
730
            if ($childProcessStatus !== 0) {
×
731
                $success = false;
×
732
            }
733

734
            $out = $childProcs[$pid];
×
735
            unset($childProcs[$pid]);
×
736
            if (file_exists($out) === false) {
×
737
                continue;
×
738
            }
739

740
            include $out;
×
741
            unlink($out);
×
742

743
            $numProcessed++;
×
744

745
            if (isset($childOutput) === false) {
×
746
                // The child process died, so the run has failed.
747
                $file = new DummyFile('', $this->ruleset, $this->config);
×
748
                $file->setErrorCounts(1, 0, 0, 0);
×
749
                $this->printProgress($file, $totalBatches, $numProcessed);
×
750
                $success = false;
×
751
                continue;
×
752
            }
753

754
            $this->reporter->totalFiles    += $childOutput['totalFiles'];
×
755
            $this->reporter->totalErrors   += $childOutput['totalErrors'];
×
756
            $this->reporter->totalWarnings += $childOutput['totalWarnings'];
×
757
            $this->reporter->totalFixable  += $childOutput['totalFixable'];
×
758
            $this->reporter->totalFixed    += $childOutput['totalFixed'];
×
759

760
            if (isset($debugOutput) === true) {
×
761
                echo $debugOutput;
×
762
            }
763

764
            if (isset($childCache) === true) {
×
765
                foreach ($childCache as $path => $cache) {
×
766
                    Cache::set($path, $cache);
×
767
                }
768
            }
769

770
            // Fake a processed file so we can print progress output for the batch.
771
            $file = new DummyFile('', $this->ruleset, $this->config);
×
772
            $file->setErrorCounts(
×
773
                $childOutput['totalErrors'],
×
774
                $childOutput['totalWarnings'],
×
775
                $childOutput['totalFixable'],
×
776
                $childOutput['totalFixed']
×
777
            );
778
            $this->printProgress($file, $totalBatches, $numProcessed);
×
779
        }//end while
780

781
        return $success;
×
782

783
    }//end processChildProcs()
784

785

786
    /**
787
     * Print progress information for a single processed file.
788
     *
789
     * @param \PHP_CodeSniffer\Files\File $file         The file that was processed.
790
     * @param int                         $numFiles     The total number of files to process.
791
     * @param int                         $numProcessed The number of files that have been processed,
792
     *                                                  including this one.
793
     *
794
     * @return void
795
     */
796
    public function printProgress(File $file, $numFiles, $numProcessed)
63✔
797
    {
798
        if (PHP_CODESNIFFER_VERBOSITY > 0
63✔
799
            || $this->config->showProgress === false
63✔
800
        ) {
801
            return;
3✔
802
        }
803

804
        $showColors  = $this->config->colors;
60✔
805
        $colorOpen   = '';
60✔
806
        $progressDot = '.';
60✔
807
        $colorClose  = '';
60✔
808

809
        // Show progress information.
810
        if ($file->ignored === true) {
60✔
811
            $progressDot = 'S';
3✔
812
        } else {
813
            $errors   = $file->getErrorCount();
60✔
814
            $warnings = $file->getWarningCount();
60✔
815
            $fixable  = $file->getFixableCount();
60✔
816
            $fixed    = $file->getFixedCount();
60✔
817

818
            if (PHP_CODESNIFFER_CBF === true) {
60✔
819
                // Files with fixed errors or warnings are F (green).
820
                // Files with unfixable errors or warnings are E (red).
821
                // Files with no errors or warnings are . (black).
822
                if ($fixable > 0) {
18✔
823
                    $progressDot = 'E';
6✔
824

825
                    if ($showColors === true) {
6✔
826
                        $colorOpen  = "\033[31m";
3✔
827
                        $colorClose = "\033[0m";
5✔
828
                    }
829
                } else if ($fixed > 0) {
12✔
830
                    $progressDot = 'F';
6✔
831

832
                    if ($showColors === true) {
6✔
833
                        $colorOpen  = "\033[32m";
3✔
834
                        $colorClose = "\033[0m";
13✔
835
                    }
836
                }//end if
837
            } else {
838
                // Files with errors are E (red).
839
                // Files with fixable errors are E (green).
840
                // Files with warnings are W (yellow).
841
                // Files with fixable warnings are W (green).
842
                // Files with no errors or warnings are . (black).
843
                if ($errors > 0) {
42✔
844
                    $progressDot = 'E';
9✔
845

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

853
                        $colorClose = "\033[0m";
8✔
854
                    }
855
                } else if ($warnings > 0) {
33✔
856
                    $progressDot = 'W';
9✔
857

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

865
                        $colorClose = "\033[0m";
6✔
866
                    }
867
                }//end if
868
            }//end if
869
        }//end if
870

871
        StatusWriter::write($colorOpen.$progressDot.$colorClose, 0, 0);
60✔
872

873
        $numPerLine = 60;
60✔
874
        if ($numProcessed !== $numFiles && ($numProcessed % $numPerLine) !== 0) {
60✔
875
            return;
60✔
876
        }
877

878
        $percent = round(($numProcessed / $numFiles) * 100);
18✔
879
        $padding = (strlen($numFiles) - strlen($numProcessed));
18✔
880
        if ($numProcessed === $numFiles
18✔
881
            && $numFiles > $numPerLine
18✔
882
            && ($numProcessed % $numPerLine) !== 0
18✔
883
        ) {
884
            $padding += ($numPerLine - ($numFiles - (floor($numFiles / $numPerLine) * $numPerLine)));
9✔
885
        }
886

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

889
    }//end printProgress()
6✔
890

891

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

914
        register_shutdown_function(
×
915
            static function () use (
916
                $errorMsg,
×
917
                $memoryError,
×
918
                $errorArray
×
919
            ) {
920
                $errorArray = error_get_last();
×
921
                if (is_array($errorArray) === true && strpos($errorArray['message'], $memoryError) !== false) {
×
922
                    fwrite(STDERR, $errorMsg);
×
923
                }
924
            }
×
925
        );
926

927
    }//end registerOutOfMemoryShutdownMessage()
928

929

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