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

PHPCSStandards / PHP_CodeSniffer / 13753331620

09 Mar 2025 10:51PM UTC coverage: 78.621% (+0.07%) from 78.556%
13753331620

Pull #857

github

web-flow
Merge 94a9e77ce into 575523895
Pull Request #857: Ruleset: improve error handling

121 of 126 new or added lines in 2 files covered. (96.03%)

5 existing lines in 2 files now uncovered.

24794 of 31536 relevant lines covered (78.62%)

66.31 hits per line

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

5.9
/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

28
class Runner
29
{
30

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

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

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

52

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

62
        try {
63
            Timing::startTiming();
8✔
64
            Runner::checkRequirements();
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
                }
1✔
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
                }
2✔
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
            $toScreen = $this->reporter->printReports();
×
124

125
            // Only print timer output if no reports were
126
            // printed to the screen so we don't put additional output
127
            // in something like an XML report. If we are printing to screen,
128
            // the report types would have already worked out who should
129
            // print the timer info.
130
            if ($this->config->interactive === false
1✔
131
                && ($toScreen === false
×
132
                || (($this->reporter->totalErrors + $this->reporter->totalWarnings) === 0 && $this->config->showProgress === true))
×
133
            ) {
134
                Timing::printRunTime();
×
135
            }
136
        } catch (DeepExitException $e) {
×
137
            echo $e->getMessage();
×
138
            return $e->getCode();
×
139
        }//end try
140

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

152
    }//end runPHPCS()
153

154

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

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

168
        try {
169
            Timing::startTiming();
×
170
            Runner::checkRequirements();
×
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
            echo PHP_EOL;
×
220
            Timing::printRunTime();
×
221
        } catch (DeepExitException $e) {
×
222
            echo $e->getMessage();
×
223
            return $e->getCode();
×
224
        }//end try
225

226
        if ($this->reporter->totalFixed === 0) {
×
227
            // Nothing was fixed by PHPCBF.
228
            if ($this->reporter->totalFixable === 0) {
×
229
                // Nothing found that could be fixed.
230
                return 0;
×
231
            } else {
232
                // Something failed to fix.
233
                return 2;
×
234
            }
235
        }
236

237
        if ($this->reporter->totalFixable === 0) {
×
238
            // PHPCBF fixed all fixable errors.
239
            return 1;
×
240
        }
241

242
        // PHPCBF fixed some fixable errors, but others failed to fix.
243
        return 2;
×
244

245
    }//end runPHPCBF()
246

247

248
    /**
249
     * Exits if the minimum requirements of PHP_CodeSniffer are not met.
250
     *
251
     * @return void
252
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the requirements are not met.
253
     */
254
    public function checkRequirements()
×
255
    {
256
        // Check the PHP version.
257
        if (PHP_VERSION_ID < 50400) {
×
258
            $error = 'ERROR: PHP_CodeSniffer requires PHP version 5.4.0 or greater.'.PHP_EOL;
×
259
            throw new DeepExitException($error, 3);
×
260
        }
261

262
        $requiredExtensions = [
263
            'tokenizer',
×
264
            'xmlwriter',
265
            'SimpleXML',
266
        ];
267
        $missingExtensions  = [];
×
268

269
        foreach ($requiredExtensions as $extension) {
×
270
            if (extension_loaded($extension) === false) {
×
271
                $missingExtensions[] = $extension;
×
272
            }
273
        }
274

275
        if (empty($missingExtensions) === false) {
×
276
            $last      = array_pop($requiredExtensions);
×
277
            $required  = implode(', ', $requiredExtensions);
×
278
            $required .= ' and '.$last;
×
279

280
            if (count($missingExtensions) === 1) {
×
281
                $missing = $missingExtensions[0];
×
282
            } else {
283
                $last     = array_pop($missingExtensions);
×
284
                $missing  = implode(', ', $missingExtensions);
×
285
                $missing .= ' and '.$last;
×
286
            }
287

288
            $error = 'ERROR: PHP_CodeSniffer requires the %s extensions to be enabled. Please enable %s.'.PHP_EOL;
×
289
            $error = sprintf($error, $required, $missing);
×
290
            throw new DeepExitException($error, 3);
×
291
        }
292

293
    }//end checkRequirements()
294

295

296
    /**
297
     * Init the rulesets and other high-level settings.
298
     *
299
     * @return void
300
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If a referenced standard is not installed.
301
     */
302
    public function init()
×
303
    {
304
        if (defined('PHP_CODESNIFFER_CBF') === false) {
×
305
            define('PHP_CODESNIFFER_CBF', false);
×
306
        }
307

308
        // Ensure this option is enabled or else line endings will not always
309
        // be detected properly for files created on a Mac with the /r line ending.
310
        @ini_set('auto_detect_line_endings', true);
×
311

312
        // Disable the PCRE JIT as this caused issues with parallel running.
313
        ini_set('pcre.jit', false);
×
314

315
        // Check that the standards are valid.
316
        foreach ($this->config->standards as $standard) {
×
317
            if (Standards::isInstalledStandard($standard) === false) {
×
318
                // They didn't select a valid coding standard, so help them
319
                // out by letting them know which standards are installed.
320
                $error = 'ERROR: the "'.$standard.'" coding standard is not installed. ';
×
321
                ob_start();
×
322
                Standards::printInstalledStandards();
×
323
                $error .= ob_get_contents();
×
324
                ob_end_clean();
×
325
                throw new DeepExitException($error, 3);
×
326
            }
327
        }
328

329
        // Saves passing the Config object into other objects that only need
330
        // the verbosity flag for debug output.
331
        if (defined('PHP_CODESNIFFER_VERBOSITY') === false) {
×
332
            define('PHP_CODESNIFFER_VERBOSITY', $this->config->verbosity);
×
333
        }
334

335
        // Create this class so it is autoloaded and sets up a bunch
336
        // of PHP_CodeSniffer-specific token type constants.
337
        new Tokens();
×
338

339
        // Allow autoloading of custom files inside installed standards.
340
        $installedStandards = Standards::getInstalledStandardDetails();
×
341
        foreach ($installedStandards as $details) {
×
342
            Autoload::addSearchPath($details['path'], $details['namespace']);
×
343
        }
344

345
        // The ruleset contains all the information about how the files
346
        // should be checked and/or fixed.
347
        try {
348
            $this->ruleset = new Ruleset($this->config);
×
349

350
            if ($this->ruleset->hasSniffDeprecations() === true) {
×
351
                $this->ruleset->showSniffDeprecations();
×
352
            }
353
        } catch (RuntimeException $e) {
×
354
            $error  = rtrim($e->getMessage(), "\r\n").PHP_EOL.PHP_EOL;
×
355
            $error .= $this->config->printShortUsage(true);
×
356
            throw new DeepExitException($error, 3);
×
357
        }
358

359
    }//end init()
360

361

362
    /**
363
     * Performs the run.
364
     *
365
     * @return int The number of errors and warnings found.
366
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
367
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException
368
     */
369
    private function run()
×
370
    {
371
        // The class that manages all reporters for the run.
372
        $this->reporter = new Reporter($this->config);
×
373

374
        // Include bootstrap files.
375
        foreach ($this->config->bootstrap as $bootstrap) {
×
376
            include $bootstrap;
×
377
        }
378

379
        if ($this->config->stdin === true) {
×
380
            $fileContents = $this->config->stdinContent;
×
381
            if ($fileContents === null) {
×
382
                $handle = fopen('php://stdin', 'r');
×
383
                stream_set_blocking($handle, true);
×
384
                $fileContents = stream_get_contents($handle);
×
385
                fclose($handle);
×
386
            }
387

388
            $todo  = new FileList($this->config, $this->ruleset);
×
389
            $dummy = new DummyFile($fileContents, $this->ruleset, $this->config);
×
390
            $todo->addFile($dummy->path, $dummy);
×
391
        } else {
392
            if (empty($this->config->files) === true) {
×
393
                $error  = 'ERROR: You must supply at least one file or directory to process.'.PHP_EOL.PHP_EOL;
×
394
                $error .= $this->config->printShortUsage(true);
×
395
                throw new DeepExitException($error, 3);
×
396
            }
397

398
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
399
                echo 'Creating file list... ';
×
400
            }
401

402
            $todo = new FileList($this->config, $this->ruleset);
×
403

404
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
405
                $numFiles = count($todo);
×
406
                echo "DONE ($numFiles files in queue)".PHP_EOL;
×
407
            }
408

409
            if ($this->config->cache === true) {
×
410
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
411
                    echo 'Loading cache... ';
×
412
                }
413

414
                Cache::load($this->ruleset, $this->config);
×
415

416
                if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
417
                    $size = Cache::getSize();
×
418
                    echo "DONE ($size files in cache)".PHP_EOL;
×
419
                }
420
            }
421
        }//end if
422

423
        // Turn all sniff errors into exceptions.
424
        set_error_handler([$this, 'handleErrors']);
×
425

426
        // If verbosity is too high, turn off parallelism so the
427
        // debug output is clean.
428
        if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
429
            $this->config->parallel = 1;
×
430
        }
431

432
        // If the PCNTL extension isn't installed, we can't fork.
433
        if (function_exists('pcntl_fork') === false) {
×
434
            $this->config->parallel = 1;
×
435
        }
436

437
        $lastDir  = '';
×
438
        $numFiles = count($todo);
×
439

440
        if ($this->config->parallel === 1) {
×
441
            // Running normally.
442
            $numProcessed = 0;
×
443
            foreach ($todo as $path => $file) {
×
444
                if ($file->ignored === false) {
×
445
                    $currDir = dirname($path);
×
446
                    if ($lastDir !== $currDir) {
×
447
                        if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
448
                            echo 'Changing into directory '.Common::stripBasepath($currDir, $this->config->basepath).PHP_EOL;
×
449
                        }
450

451
                        $lastDir = $currDir;
×
452
                    }
453

454
                    $this->processFile($file);
×
455
                } else if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
456
                    echo 'Skipping '.basename($file->path).PHP_EOL;
×
457
                }
458

459
                $numProcessed++;
×
460
                $this->printProgress($file, $numFiles, $numProcessed);
×
461
            }
462
        } else {
463
            // Batching and forking.
464
            $childProcs  = [];
×
465
            $numPerBatch = ceil($numFiles / $this->config->parallel);
×
466

467
            for ($batch = 0; $batch < $this->config->parallel; $batch++) {
×
468
                $startAt = ($batch * $numPerBatch);
×
469
                if ($startAt >= $numFiles) {
×
470
                    break;
×
471
                }
472

473
                $endAt = ($startAt + $numPerBatch);
×
474
                if ($endAt > $numFiles) {
×
475
                    $endAt = $numFiles;
×
476
                }
477

478
                $childOutFilename = tempnam(sys_get_temp_dir(), 'phpcs-child');
×
479
                $pid = pcntl_fork();
×
480
                if ($pid === -1) {
×
481
                    throw new RuntimeException('Failed to create child process');
×
482
                } else if ($pid !== 0) {
×
483
                    $childProcs[$pid] = $childOutFilename;
×
484
                } else {
485
                    // Move forward to the start of the batch.
486
                    $todo->rewind();
×
487
                    for ($i = 0; $i < $startAt; $i++) {
×
488
                        $todo->next();
×
489
                    }
490

491
                    // Reset the reporter to make sure only figures from this
492
                    // file batch are recorded.
493
                    $this->reporter->totalFiles    = 0;
×
494
                    $this->reporter->totalErrors   = 0;
×
495
                    $this->reporter->totalWarnings = 0;
×
496
                    $this->reporter->totalFixable  = 0;
×
497
                    $this->reporter->totalFixed    = 0;
×
498

499
                    // Process the files.
500
                    $pathsProcessed = [];
×
501
                    ob_start();
×
502
                    for ($i = $startAt; $i < $endAt; $i++) {
×
503
                        $path = $todo->key();
×
504
                        $file = $todo->current();
×
505

506
                        if ($file->ignored === true) {
×
507
                            $todo->next();
×
508
                            continue;
×
509
                        }
510

511
                        $currDir = dirname($path);
×
512
                        if ($lastDir !== $currDir) {
×
513
                            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
514
                                echo 'Changing into directory '.Common::stripBasepath($currDir, $this->config->basepath).PHP_EOL;
×
515
                            }
516

517
                            $lastDir = $currDir;
×
518
                        }
519

520
                        $this->processFile($file);
×
521

522
                        $pathsProcessed[] = $path;
×
523
                        $todo->next();
×
524
                    }//end for
525

526
                    $debugOutput = ob_get_contents();
×
527
                    ob_end_clean();
×
528

529
                    // Write information about the run to the filesystem
530
                    // so it can be picked up by the main process.
531
                    $childOutput = [
532
                        'totalFiles'    => $this->reporter->totalFiles,
×
533
                        'totalErrors'   => $this->reporter->totalErrors,
×
534
                        'totalWarnings' => $this->reporter->totalWarnings,
×
535
                        'totalFixable'  => $this->reporter->totalFixable,
×
536
                        'totalFixed'    => $this->reporter->totalFixed,
×
537
                    ];
538

539
                    $output  = '<'.'?php'."\n".' $childOutput = ';
×
540
                    $output .= var_export($childOutput, true);
×
541
                    $output .= ";\n\$debugOutput = ";
×
542
                    $output .= var_export($debugOutput, true);
×
543

544
                    if ($this->config->cache === true) {
×
545
                        $childCache = [];
×
546
                        foreach ($pathsProcessed as $path) {
×
547
                            $childCache[$path] = Cache::get($path);
×
548
                        }
549

550
                        $output .= ";\n\$childCache = ";
×
551
                        $output .= var_export($childCache, true);
×
552
                    }
553

554
                    $output .= ";\n?".'>';
×
555
                    file_put_contents($childOutFilename, $output);
×
556
                    exit();
×
557
                }//end if
558
            }//end for
559

560
            $success = $this->processChildProcs($childProcs);
×
561
            if ($success === false) {
×
562
                throw new RuntimeException('One or more child processes failed to run');
×
563
            }
564
        }//end if
565

566
        restore_error_handler();
×
567

568
        if (PHP_CODESNIFFER_VERBOSITY === 0
×
569
            && $this->config->interactive === false
×
570
            && $this->config->showProgress === true
×
571
        ) {
572
            echo PHP_EOL.PHP_EOL;
×
573
        }
574

575
        if ($this->config->cache === true) {
×
576
            Cache::save();
×
577
        }
578

579
        $ignoreWarnings = Config::getConfigData('ignore_warnings_on_exit');
×
580
        $ignoreErrors   = Config::getConfigData('ignore_errors_on_exit');
×
581

582
        $return = ($this->reporter->totalErrors + $this->reporter->totalWarnings);
×
583
        if ($ignoreErrors !== null) {
×
584
            $ignoreErrors = (bool) $ignoreErrors;
×
585
            if ($ignoreErrors === true) {
×
586
                $return -= $this->reporter->totalErrors;
×
587
            }
588
        }
589

590
        if ($ignoreWarnings !== null) {
×
591
            $ignoreWarnings = (bool) $ignoreWarnings;
×
592
            if ($ignoreWarnings === true) {
×
593
                $return -= $this->reporter->totalWarnings;
×
594
            }
595
        }
596

597
        return $return;
×
598

599
    }//end run()
600

601

602
    /**
603
     * Converts all PHP errors into exceptions.
604
     *
605
     * This method forces a sniff to stop processing if it is not
606
     * able to handle a specific piece of code, instead of continuing
607
     * and potentially getting into a loop.
608
     *
609
     * @param int    $code    The level of error raised.
610
     * @param string $message The error message.
611
     * @param string $file    The path of the file that raised the error.
612
     * @param int    $line    The line number the error was raised at.
613
     *
614
     * @return bool
615
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException
616
     */
617
    public function handleErrors($code, $message, $file, $line)
×
618
    {
619
        if ((error_reporting() & $code) === 0) {
×
620
            // This type of error is being muted.
621
            return true;
×
622
        }
623

624
        throw new RuntimeException("$message in $file on line $line");
×
625

626
    }//end handleErrors()
627

628

629
    /**
630
     * Processes a single file, including checking and fixing.
631
     *
632
     * @param \PHP_CodeSniffer\Files\File $file The file to be processed.
633
     *
634
     * @return void
635
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
636
     */
637
    public function processFile($file)
×
638
    {
639
        if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
640
            $startTime = microtime(true);
×
641
            echo 'Processing '.basename($file->path).' ';
×
642
            if (PHP_CODESNIFFER_VERBOSITY > 1) {
×
643
                echo PHP_EOL;
×
644
            }
645
        }
646

647
        try {
648
            $file->process();
×
649

650
            if (PHP_CODESNIFFER_VERBOSITY > 0) {
×
651
                $timeTaken = ((microtime(true) - $startTime) * 1000);
×
652
                if ($timeTaken < 1000) {
×
653
                    $timeTaken = round($timeTaken);
×
654
                    echo "DONE in {$timeTaken}ms";
×
655
                } else {
656
                    $timeTaken = round(($timeTaken / 1000), 2);
×
657
                    echo "DONE in $timeTaken secs";
×
658
                }
659

660
                if (PHP_CODESNIFFER_CBF === true) {
×
661
                    $errors = $file->getFixableCount();
×
662
                    echo " ($errors fixable violations)".PHP_EOL;
×
663
                } else {
664
                    $errors   = $file->getErrorCount();
×
665
                    $warnings = $file->getWarningCount();
×
666
                    echo " ($errors errors, $warnings warnings)".PHP_EOL;
×
667
                }
668
            }
669
        } catch (Exception $e) {
×
670
            $error = 'An error occurred during processing; checking has been aborted. The error message was: '.$e->getMessage();
×
671

672
            // Determine which sniff caused the error.
673
            $sniffStack = null;
×
674
            $nextStack  = null;
×
675
            foreach ($e->getTrace() as $step) {
×
676
                if (isset($step['file']) === false) {
×
677
                    continue;
×
678
                }
679

680
                if (empty($sniffStack) === false) {
×
681
                    $nextStack = $step;
×
682
                    break;
×
683
                }
684

685
                if (substr($step['file'], -9) === 'Sniff.php') {
×
686
                    $sniffStack = $step;
×
687
                    continue;
×
688
                }
689
            }
690

691
            if (empty($sniffStack) === false) {
×
692
                $sniffCode = '';
×
693
                try {
694
                    if (empty($nextStack) === false
×
695
                        && isset($nextStack['class']) === true
×
696
                        && substr($nextStack['class'], -5) === 'Sniff'
×
697
                    ) {
698
                        $sniffCode = 'the '.Common::getSniffCode($nextStack['class']).' sniff';
×
699
                    }
700
                } catch (InvalidArgumentException $e) {
×
701
                    // Sniff code could not be determined. This may be an abstract sniff class.
702
                }
703

704
                if ($sniffCode === '') {
×
705
                    $sniffCode = substr(strrchr(str_replace('\\', '/', $sniffStack['file']), '/'), 1);
×
706
                }
707

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

711
            $file->addErrorOnLine($error, 1, 'Internal.Exception');
×
712
        }//end try
713

714
        $this->reporter->cacheFileReport($file);
×
715

716
        if ($this->config->interactive === true) {
×
717
            /*
718
                Running interactively.
719
                Print the error report for the current file and then wait for user input.
720
            */
721

722
            // Get current violations and then clear the list to make sure
723
            // we only print violations for a single file each time.
724
            $numErrors = null;
×
725
            while ($numErrors !== 0) {
×
726
                $numErrors = ($file->getErrorCount() + $file->getWarningCount());
×
727
                if ($numErrors === 0) {
×
728
                    continue;
×
729
                }
730

731
                $this->reporter->printReport('full');
×
732

733
                echo '<ENTER> to recheck, [s] to skip or [q] to quit : ';
×
734
                $input = fgets(STDIN);
×
735
                $input = trim($input);
×
736

737
                switch ($input) {
738
                case 's':
×
739
                    break(2);
×
740
                case 'q':
×
741
                    throw new DeepExitException('', 0);
×
742
                default:
743
                    // Repopulate the sniffs because some of them save their state
744
                    // and only clear it when the file changes, but we are rechecking
745
                    // the same file.
746
                    $file->ruleset->populateTokenListeners();
×
747
                    $file->reloadContent();
×
748
                    $file->process();
×
749
                    $this->reporter->cacheFileReport($file);
×
750
                    break;
×
751
                }
752
            }//end while
753
        }//end if
754

755
        // Clean up the file to save (a lot of) memory.
756
        $file->cleanUp();
×
757

758
    }//end processFile()
759

760

761
    /**
762
     * Waits for child processes to complete and cleans up after them.
763
     *
764
     * The reporting information returned by each child process is merged
765
     * into the main reporter class.
766
     *
767
     * @param array $childProcs An array of child processes to wait for.
768
     *
769
     * @return bool
770
     */
771
    private function processChildProcs($childProcs)
×
772
    {
773
        $numProcessed = 0;
×
774
        $totalBatches = count($childProcs);
×
775

776
        $success = true;
×
777

778
        while (count($childProcs) > 0) {
×
779
            $pid = pcntl_waitpid(0, $status);
×
780
            if ($pid <= 0) {
×
781
                continue;
×
782
            }
783

784
            $childProcessStatus = pcntl_wexitstatus($status);
×
785
            if ($childProcessStatus !== 0) {
×
786
                $success = false;
×
787
            }
788

789
            $out = $childProcs[$pid];
×
790
            unset($childProcs[$pid]);
×
791
            if (file_exists($out) === false) {
×
792
                continue;
×
793
            }
794

795
            include $out;
×
796
            unlink($out);
×
797

798
            $numProcessed++;
×
799

800
            if (isset($childOutput) === false) {
×
801
                // The child process died, so the run has failed.
802
                $file = new DummyFile('', $this->ruleset, $this->config);
×
803
                $file->setErrorCounts(1, 0, 0, 0);
×
804
                $this->printProgress($file, $totalBatches, $numProcessed);
×
805
                $success = false;
×
806
                continue;
×
807
            }
808

809
            $this->reporter->totalFiles    += $childOutput['totalFiles'];
×
810
            $this->reporter->totalErrors   += $childOutput['totalErrors'];
×
811
            $this->reporter->totalWarnings += $childOutput['totalWarnings'];
×
812
            $this->reporter->totalFixable  += $childOutput['totalFixable'];
×
813
            $this->reporter->totalFixed    += $childOutput['totalFixed'];
×
814

815
            if (isset($debugOutput) === true) {
×
816
                echo $debugOutput;
×
817
            }
818

819
            if (isset($childCache) === true) {
×
820
                foreach ($childCache as $path => $cache) {
×
821
                    Cache::set($path, $cache);
×
822
                }
823
            }
824

825
            // Fake a processed file so we can print progress output for the batch.
826
            $file = new DummyFile('', $this->ruleset, $this->config);
×
827
            $file->setErrorCounts(
×
828
                $childOutput['totalErrors'],
×
829
                $childOutput['totalWarnings'],
×
830
                $childOutput['totalFixable'],
×
831
                $childOutput['totalFixed']
×
832
            );
833
            $this->printProgress($file, $totalBatches, $numProcessed);
×
834
        }//end while
835

836
        return $success;
×
837

838
    }//end processChildProcs()
839

840

841
    /**
842
     * Print progress information for a single processed file.
843
     *
844
     * @param \PHP_CodeSniffer\Files\File $file         The file that was processed.
845
     * @param int                         $numFiles     The total number of files to process.
846
     * @param int                         $numProcessed The number of files that have been processed,
847
     *                                                  including this one.
848
     *
849
     * @return void
850
     */
851
    public function printProgress(File $file, $numFiles, $numProcessed)
×
852
    {
853
        if (PHP_CODESNIFFER_VERBOSITY > 0
×
854
            || $this->config->showProgress === false
×
855
        ) {
856
            return;
×
857
        }
858

859
        // Show progress information.
860
        if ($file->ignored === true) {
×
861
            echo 'S';
×
862
        } else {
863
            $errors   = $file->getErrorCount();
×
864
            $warnings = $file->getWarningCount();
×
865
            $fixable  = $file->getFixableCount();
×
866
            $fixed    = $file->getFixedCount();
×
867

868
            if (PHP_CODESNIFFER_CBF === true) {
×
869
                // Files with fixed errors or warnings are F (green).
870
                // Files with unfixable errors or warnings are E (red).
871
                // Files with no errors or warnings are . (black).
872
                if ($fixable > 0) {
×
873
                    if ($this->config->colors === true) {
×
874
                        echo "\033[31m";
×
875
                    }
876

877
                    echo 'E';
×
878

879
                    if ($this->config->colors === true) {
×
880
                        echo "\033[0m";
×
881
                    }
882
                } else if ($fixed > 0) {
×
883
                    if ($this->config->colors === true) {
×
884
                        echo "\033[32m";
×
885
                    }
886

887
                    echo 'F';
×
888

889
                    if ($this->config->colors === true) {
×
890
                        echo "\033[0m";
×
891
                    }
892
                } else {
893
                    echo '.';
×
894
                }//end if
895
            } else {
896
                // Files with errors are E (red).
897
                // Files with fixable errors are E (green).
898
                // Files with warnings are W (yellow).
899
                // Files with fixable warnings are W (green).
900
                // Files with no errors or warnings are . (black).
901
                if ($errors > 0) {
×
902
                    if ($this->config->colors === true) {
×
903
                        if ($fixable > 0) {
×
904
                            echo "\033[32m";
×
905
                        } else {
906
                            echo "\033[31m";
×
907
                        }
908
                    }
909

910
                    echo 'E';
×
911

912
                    if ($this->config->colors === true) {
×
913
                        echo "\033[0m";
×
914
                    }
915
                } else if ($warnings > 0) {
×
916
                    if ($this->config->colors === true) {
×
917
                        if ($fixable > 0) {
×
918
                            echo "\033[32m";
×
919
                        } else {
920
                            echo "\033[33m";
×
921
                        }
922
                    }
923

924
                    echo 'W';
×
925

926
                    if ($this->config->colors === true) {
×
927
                        echo "\033[0m";
×
928
                    }
929
                } else {
930
                    echo '.';
×
931
                }//end if
932
            }//end if
933
        }//end if
934

935
        $numPerLine = 60;
×
936
        if ($numProcessed !== $numFiles && ($numProcessed % $numPerLine) !== 0) {
×
937
            return;
×
938
        }
939

940
        $percent = round(($numProcessed / $numFiles) * 100);
×
941
        $padding = (strlen($numFiles) - strlen($numProcessed));
×
942
        if ($numProcessed === $numFiles
943
            && $numFiles > $numPerLine
×
944
            && ($numProcessed % $numPerLine) !== 0
×
945
        ) {
946
            $padding += ($numPerLine - ($numFiles - (floor($numFiles / $numPerLine) * $numPerLine)));
×
947
        }
948

949
        echo str_repeat(' ', $padding)." $numProcessed / $numFiles ($percent%)".PHP_EOL;
×
950

951
    }//end printProgress()
952

953

954
    /**
955
     * Registers a PHP shutdown function to provide a more informative out of memory error.
956
     *
957
     * @param string $command The command which was used to initiate the PHPCS run.
958
     *
959
     * @return void
960
     */
961
    private function registerOutOfMemoryShutdownMessage($command)
×
962
    {
963
        // Allocate all needed memory beforehand as much as possible.
964
        $errorMsg    = PHP_EOL.'The PHP_CodeSniffer "%1$s" command ran out of memory.'.PHP_EOL;
×
965
        $errorMsg   .= 'Either raise the "memory_limit" of PHP in the php.ini file or raise the memory limit at runtime'.PHP_EOL;
×
966
        $errorMsg   .= 'using `%1$s -d memory_limit=512M` (replace 512M with the desired memory limit).'.PHP_EOL;
×
967
        $errorMsg    = sprintf($errorMsg, $command);
×
968
        $memoryError = 'Allowed memory size of';
×
969
        $errorArray  = [
970
            'type'    => 42,
×
971
            'message' => 'Some random dummy string to take up memory and take up some more memory and some more',
972
            'file'    => 'Another random string, which would be a filename this time. Should be relatively long to allow for deeply nested files',
973
            'line'    => 31427,
974
        ];
975

976
        register_shutdown_function(
×
977
            static function () use (
978
                $errorMsg,
×
979
                $memoryError,
×
980
                $errorArray
×
981
            ) {
982
                $errorArray = error_get_last();
×
983
                if (is_array($errorArray) === true && strpos($errorArray['message'], $memoryError) !== false) {
×
984
                    echo $errorMsg;
×
985
                }
986
            }
×
987
        );
988

989
    }//end registerOutOfMemoryShutdownMessage()
990

991

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