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

PHPCSStandards / PHP_CodeSniffer / 13506314473

24 Feb 2025 07:34PM UTC coverage: 78.585% (+0.1%) from 78.468%
13506314473

Pull #812

github

web-flow
Merge 6ed9ac8b2 into bf2b64d00
Pull Request #812: Tests/Tokenizer: improve switch keyword tests

24737 of 31478 relevant lines covered (78.59%)

66.37 hits per line

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

32.14
/src/Config.php
1
<?php
2
/**
3
 * Stores the configuration used to run PHPCS and PHPCBF.
4
 *
5
 * Parses the command line to determine user supplied values
6
 * and provides functions to access data stored in config files.
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 Phar;
17
use PHP_CodeSniffer\Exceptions\DeepExitException;
18
use PHP_CodeSniffer\Exceptions\RuntimeException;
19
use PHP_CodeSniffer\Util\Common;
20
use PHP_CodeSniffer\Util\Help;
21
use PHP_CodeSniffer\Util\Standards;
22

23
/**
24
 * Stores the configuration used to run PHPCS and PHPCBF.
25
 *
26
 * @property string[]   $files           The files and directories to check.
27
 * @property string[]   $standards       The standards being used for checking.
28
 * @property int        $verbosity       How verbose the output should be.
29
 *                                       0: no unnecessary output
30
 *                                       1: basic output for files being checked
31
 *                                       2: ruleset and file parsing output
32
 *                                       3: sniff execution output
33
 * @property bool       $interactive     Enable interactive checking mode.
34
 * @property int        $parallel        Check files in parallel.
35
 * @property bool       $cache           Enable the use of the file cache.
36
 * @property string     $cacheFile       Path to the file where the cache data should be written
37
 * @property bool       $colors          Display colours in output.
38
 * @property bool       $explain         Explain the coding standards.
39
 * @property bool       $local           Process local files in directories only (no recursion).
40
 * @property bool       $showSources     Show sniff source codes in report output.
41
 * @property bool       $showProgress    Show basic progress information while running.
42
 * @property bool       $quiet           Quiet mode; disables progress and verbose output.
43
 * @property bool       $annotations     Process phpcs: annotations.
44
 * @property int        $tabWidth        How many spaces each tab is worth.
45
 * @property string     $encoding        The encoding of the files being checked.
46
 * @property string[]   $sniffs          The sniffs that should be used for checking.
47
 *                                       If empty, all sniffs in the supplied standards will be used.
48
 * @property string[]   $exclude         The sniffs that should be excluded from checking.
49
 *                                       If empty, all sniffs in the supplied standards will be used.
50
 * @property string[]   $ignored         Regular expressions used to ignore files and folders during checking.
51
 * @property string     $reportFile      A file where the report output should be written.
52
 * @property string     $generator       The documentation generator to use.
53
 * @property string     $filter          The filter to use for the run.
54
 * @property string[]   $bootstrap       One of more files to include before the run begins.
55
 * @property int|string $reportWidth     The maximum number of columns that reports should use for output.
56
 *                                       Set to "auto" for have this value changed to the width of the terminal.
57
 * @property int        $errorSeverity   The minimum severity an error must have to be displayed.
58
 * @property int        $warningSeverity The minimum severity a warning must have to be displayed.
59
 * @property bool       $recordErrors    Record the content of error messages as well as error counts.
60
 * @property string     $suffix          A suffix to add to fixed files.
61
 * @property string     $basepath        A file system location to strip from the paths of files shown in reports.
62
 * @property bool       $stdin           Read content from STDIN instead of supplied files.
63
 * @property string     $stdinContent    Content passed directly to PHPCS on STDIN.
64
 * @property string     $stdinPath       The path to use for content passed on STDIN.
65
 * @property bool       $trackTime       Whether or not to track sniff run time.
66
 *
67
 * @property array<string, string>      $extensions File extensions that should be checked, and what tokenizer to use.
68
 *                                                  E.g., array('inc' => 'PHP');
69
 * @property array<string, string|null> $reports    The reports to use for printing output after the run.
70
 *                                                  The format of the array is:
71
 *                                                      array(
72
 *                                                          'reportName1' => 'outputFile',
73
 *                                                          'reportName2' => null,
74
 *                                                      );
75
 *                                                  If the array value is NULL, the report will be written to the screen.
76
 *
77
 * @property string[] $unknown Any arguments gathered on the command line that are unknown to us.
78
 *                             E.g., using `phpcs -c` will give array('c');
79
 */
80
class Config
81
{
82

83
    /**
84
     * The current version.
85
     *
86
     * @var string
87
     */
88
    const VERSION = '3.12.0';
89

90
    /**
91
     * Package stability; either stable, beta or alpha.
92
     *
93
     * @var string
94
     */
95
    const STABILITY = 'stable';
96

97
    /**
98
     * Default report width when no report width is provided and 'auto' does not yield a valid width.
99
     *
100
     * @var int
101
     */
102
    const DEFAULT_REPORT_WIDTH = 80;
103

104
    /**
105
     * An array of settings that PHPCS and PHPCBF accept.
106
     *
107
     * This array is not meant to be accessed directly. Instead, use the settings
108
     * as if they are class member vars so the __get() and __set() magic methods
109
     * can be used to validate the values. For example, to set the verbosity level to
110
     * level 2, use $this->verbosity = 2; instead of accessing this property directly.
111
     *
112
     * Each of these settings is described in the class comment property list.
113
     *
114
     * @var array<string, mixed>
115
     */
116
    private $settings = [
117
        'files'           => null,
118
        'standards'       => null,
119
        'verbosity'       => null,
120
        'interactive'     => null,
121
        'parallel'        => null,
122
        'cache'           => null,
123
        'cacheFile'       => null,
124
        'colors'          => null,
125
        'explain'         => null,
126
        'local'           => null,
127
        'showSources'     => null,
128
        'showProgress'    => null,
129
        'quiet'           => null,
130
        'annotations'     => null,
131
        'tabWidth'        => null,
132
        'encoding'        => null,
133
        'extensions'      => null,
134
        'sniffs'          => null,
135
        'exclude'         => null,
136
        'ignored'         => null,
137
        'reportFile'      => null,
138
        'generator'       => null,
139
        'filter'          => null,
140
        'bootstrap'       => null,
141
        'reports'         => null,
142
        'basepath'        => null,
143
        'reportWidth'     => null,
144
        'errorSeverity'   => null,
145
        'warningSeverity' => null,
146
        'recordErrors'    => null,
147
        'suffix'          => null,
148
        'stdin'           => null,
149
        'stdinContent'    => null,
150
        'stdinPath'       => null,
151
        'trackTime'       => null,
152
        'unknown'         => null,
153
    ];
154

155
    /**
156
     * Whether or not to kill the process when an unknown command line arg is found.
157
     *
158
     * If FALSE, arguments that are not command line options or file/directory paths
159
     * will be ignored and execution will continue. These values will be stored in
160
     * $this->unknown.
161
     *
162
     * @var boolean
163
     */
164
    public $dieOnUnknownArg;
165

166
    /**
167
     * The current command line arguments we are processing.
168
     *
169
     * @var string[]
170
     */
171
    private $cliArgs = [];
172

173
    /**
174
     * A list of valid generators.
175
     *
176
     * {@internal Once support for PHP < 5.6 is dropped, this property should be refactored into a
177
     * class constant.}
178
     *
179
     * @var array<string, string> Keys are the lowercase version of the generator name, while values
180
     *                            are the associated PHP generator class.
181
     */
182
    private $validGenerators = [
183
        'text'     => 'Text',
184
        'html'     => 'HTML',
185
        'markdown' => 'Markdown',
186
    ];
187

188
    /**
189
     * Command line values that the user has supplied directly.
190
     *
191
     * @var array<string, true|array<string, true>>
192
     */
193
    private static $overriddenDefaults = [];
194

195
    /**
196
     * Config file data that has been loaded for the run.
197
     *
198
     * @var array<string, string>
199
     */
200
    private static $configData = null;
201

202
    /**
203
     * The full path to the config data file that has been loaded.
204
     *
205
     * @var string
206
     */
207
    private static $configDataFile = null;
208

209
    /**
210
     * Automatically discovered executable utility paths.
211
     *
212
     * @var array<string, string>
213
     */
214
    private static $executablePaths = [];
215

216

217
    /**
218
     * Get the value of an inaccessible property.
219
     *
220
     * @param string $name The name of the property.
221
     *
222
     * @return mixed
223
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the setting name is invalid.
224
     */
225
    public function __get($name)
48✔
226
    {
227
        if (array_key_exists($name, $this->settings) === false) {
48✔
228
            throw new RuntimeException("ERROR: unable to get value of property \"$name\"");
×
229
        }
230

231
        // Figure out what the terminal width needs to be for "auto".
232
        if ($name === 'reportWidth' && $this->settings[$name] === 'auto') {
48✔
233
            if (function_exists('shell_exec') === true) {
9✔
234
                $dimensions = shell_exec('stty size 2>&1');
9✔
235
                if (is_string($dimensions) === true && preg_match('|\d+ (\d+)|', $dimensions, $matches) === 1) {
9✔
236
                    $this->settings[$name] = (int) $matches[1];
×
237
                }
238
            }
3✔
239

240
            if ($this->settings[$name] === 'auto') {
9✔
241
                // If shell_exec wasn't available or didn't yield a usable value, set to the default.
242
                // This will prevent subsequent retrievals of the reportWidth from making another call to stty.
243
                $this->settings[$name] = self::DEFAULT_REPORT_WIDTH;
9✔
244
            }
3✔
245
        }
3✔
246

247
        return $this->settings[$name];
48✔
248

249
    }//end __get()
250

251

252
    /**
253
     * Set the value of an inaccessible property.
254
     *
255
     * @param string $name  The name of the property.
256
     * @param mixed  $value The value of the property.
257
     *
258
     * @return void
259
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the setting name is invalid.
260
     */
261
    public function __set($name, $value)
48✔
262
    {
263
        if (array_key_exists($name, $this->settings) === false) {
48✔
264
            throw new RuntimeException("Can't __set() $name; setting doesn't exist");
×
265
        }
266

267
        switch ($name) {
16✔
268
        case 'reportWidth' :
48✔
269
            if (is_string($value) === true && $value === 'auto') {
48✔
270
                // Nothing to do. Leave at 'auto'.
271
                break;
48✔
272
            }
273

274
            if (is_int($value) === true) {
39✔
275
                $value = abs($value);
6✔
276
            } else if (is_string($value) === true && preg_match('`^\d+$`', $value) === 1) {
35✔
277
                $value = (int) $value;
15✔
278
            } else {
5✔
279
                $value = self::DEFAULT_REPORT_WIDTH;
18✔
280
            }
281
            break;
39✔
282

283
        case 'standards' :
48✔
284
            $cleaned = [];
48✔
285

286
            // Check if the standard name is valid, or if the case is invalid.
287
            $installedStandards = Standards::getInstalledStandards();
48✔
288
            foreach ($value as $standard) {
48✔
289
                foreach ($installedStandards as $validStandard) {
48✔
290
                    if (strtolower($standard) === strtolower($validStandard)) {
48✔
291
                        $standard = $validStandard;
48✔
292
                        break;
48✔
293
                    }
294
                }
16✔
295

296
                $cleaned[] = $standard;
48✔
297
            }
16✔
298

299
            $value = $cleaned;
48✔
300
            break;
48✔
301

302
        // Only track time when explicitly needed.
303
        case 'verbosity':
48✔
304
            if ($value > 2) {
48✔
305
                $this->settings['trackTime'] = true;
×
306
            }
307
            break;
48✔
308
        case 'reports':
48✔
309
            $reports = array_change_key_case($value, CASE_LOWER);
48✔
310
            if (array_key_exists('performance', $reports) === true) {
48✔
311
                $this->settings['trackTime'] = true;
×
312
            }
313
            break;
48✔
314

315
        default :
16✔
316
            // No validation required.
317
            break;
48✔
318
        }//end switch
16✔
319

320
        $this->settings[$name] = $value;
48✔
321

322
    }//end __set()
32✔
323

324

325
    /**
326
     * Check if the value of an inaccessible property is set.
327
     *
328
     * @param string $name The name of the property.
329
     *
330
     * @return bool
331
     */
332
    public function __isset($name)
×
333
    {
334
        return isset($this->settings[$name]);
×
335

336
    }//end __isset()
337

338

339
    /**
340
     * Unset the value of an inaccessible property.
341
     *
342
     * @param string $name The name of the property.
343
     *
344
     * @return void
345
     */
346
    public function __unset($name)
×
347
    {
348
        $this->settings[$name] = null;
×
349

350
    }//end __unset()
351

352

353
    /**
354
     * Get the array of all config settings.
355
     *
356
     * @return array<string, mixed>
357
     */
358
    public function getSettings()
×
359
    {
360
        return $this->settings;
×
361

362
    }//end getSettings()
363

364

365
    /**
366
     * Set the array of all config settings.
367
     *
368
     * @param array<string, mixed> $settings The array of config settings.
369
     *
370
     * @return void
371
     */
372
    public function setSettings($settings)
×
373
    {
374
        return $this->settings = $settings;
×
375

376
    }//end setSettings()
377

378

379
    /**
380
     * Creates a Config object and populates it with command line values.
381
     *
382
     * @param array $cliArgs         An array of values gathered from CLI args.
383
     * @param bool  $dieOnUnknownArg Whether or not to kill the process when an
384
     *                               unknown command line arg is found.
385
     *
386
     * @return void
387
     */
388
    public function __construct(array $cliArgs=[], $dieOnUnknownArg=true)
×
389
    {
390
        if (defined('PHP_CODESNIFFER_IN_TESTS') === true) {
×
391
            // Let everything through during testing so that we can
392
            // make use of PHPUnit command line arguments as well.
393
            $this->dieOnUnknownArg = false;
×
394
        } else {
395
            $this->dieOnUnknownArg = $dieOnUnknownArg;
×
396
        }
397

398
        if (empty($cliArgs) === true) {
×
399
            $cliArgs = $_SERVER['argv'];
×
400
            array_shift($cliArgs);
×
401
        }
402

403
        $this->restoreDefaults();
×
404
        $this->setCommandLineValues($cliArgs);
×
405

406
        if (isset(self::$overriddenDefaults['standards']) === false) {
×
407
            // They did not supply a standard to use.
408
            // Look for a default ruleset in the current directory or higher.
409
            $currentDir = getcwd();
×
410

411
            $defaultFiles = [
412
                '.phpcs.xml',
×
413
                'phpcs.xml',
414
                '.phpcs.xml.dist',
415
                'phpcs.xml.dist',
416
            ];
417

418
            do {
419
                foreach ($defaultFiles as $defaultFilename) {
×
420
                    $default = $currentDir.DIRECTORY_SEPARATOR.$defaultFilename;
×
421
                    if (is_file($default) === true) {
×
422
                        $this->standards = [$default];
×
423
                        break(2);
×
424
                    }
425
                }
426

427
                $lastDir    = $currentDir;
×
428
                $currentDir = dirname($currentDir);
×
429
            } while ($currentDir !== '.' && $currentDir !== $lastDir && Common::isReadable($currentDir) === true);
×
430
        }//end if
431

432
        if (defined('STDIN') === false
×
433
            || stripos(PHP_OS, 'WIN') === 0
×
434
        ) {
435
            return;
×
436
        }
437

438
        $handle = fopen('php://stdin', 'r');
×
439

440
        // Check for content on STDIN.
441
        if ($this->stdin === true
×
442
            || (Common::isStdinATTY() === false
×
443
            && feof($handle) === false)
×
444
        ) {
445
            $readStreams = [$handle];
×
446
            $writeSteams = null;
×
447

448
            $fileContents = '';
×
449
            while (is_resource($handle) === true && feof($handle) === false) {
×
450
                // Set a timeout of 200ms.
451
                if (stream_select($readStreams, $writeSteams, $writeSteams, 0, 200000) === 0) {
×
452
                    break;
×
453
                }
454

455
                $fileContents .= fgets($handle);
×
456
            }
457

458
            if (trim($fileContents) !== '') {
×
459
                $this->stdin        = true;
×
460
                $this->stdinContent = $fileContents;
×
461
                self::$overriddenDefaults['stdin']        = true;
×
462
                self::$overriddenDefaults['stdinContent'] = true;
×
463
            }
464
        }//end if
465

466
        fclose($handle);
×
467

468
    }//end __construct()
469

470

471
    /**
472
     * Set the command line values.
473
     *
474
     * @param array $args An array of command line arguments to set.
475
     *
476
     * @return void
477
     */
478
    public function setCommandLineValues($args)
×
479
    {
480
        $this->cliArgs = $args;
×
481
        $numArgs       = count($args);
×
482

483
        for ($i = 0; $i < $numArgs; $i++) {
×
484
            $arg = $this->cliArgs[$i];
×
485
            if ($arg === '') {
×
486
                continue;
×
487
            }
488

489
            if ($arg[0] === '-') {
×
490
                if ($arg === '-') {
×
491
                    // Asking to read from STDIN.
492
                    $this->stdin = true;
×
493
                    self::$overriddenDefaults['stdin'] = true;
×
494
                    continue;
×
495
                }
496

497
                if ($arg === '--') {
×
498
                    // Empty argument, ignore it.
499
                    continue;
×
500
                }
501

502
                if ($arg[1] === '-') {
×
503
                    $this->processLongArgument(substr($arg, 2), $i);
×
504
                } else {
505
                    $switches = str_split($arg);
×
506
                    foreach ($switches as $switch) {
×
507
                        if ($switch === '-') {
×
508
                            continue;
×
509
                        }
510

511
                        $this->processShortArgument($switch, $i);
×
512
                    }
513
                }
514
            } else {
515
                $this->processUnknownArgument($arg, $i);
×
516
            }//end if
517
        }//end for
518

519
    }//end setCommandLineValues()
520

521

522
    /**
523
     * Restore default values for all possible command line arguments.
524
     *
525
     * @return void
526
     */
527
    public function restoreDefaults()
9✔
528
    {
529
        $this->files           = [];
9✔
530
        $this->standards       = ['PEAR'];
9✔
531
        $this->verbosity       = 0;
9✔
532
        $this->interactive     = false;
9✔
533
        $this->cache           = false;
9✔
534
        $this->cacheFile       = null;
9✔
535
        $this->colors          = false;
9✔
536
        $this->explain         = false;
9✔
537
        $this->local           = false;
9✔
538
        $this->showSources     = false;
9✔
539
        $this->showProgress    = false;
9✔
540
        $this->quiet           = false;
9✔
541
        $this->annotations     = true;
9✔
542
        $this->parallel        = 1;
9✔
543
        $this->tabWidth        = 0;
9✔
544
        $this->encoding        = 'utf-8';
9✔
545
        $this->extensions      = [
9✔
546
            'php' => 'PHP',
6✔
547
            'inc' => 'PHP',
6✔
548
            'js'  => 'JS',
6✔
549
            'css' => 'CSS',
6✔
550
        ];
3✔
551
        $this->sniffs          = [];
9✔
552
        $this->exclude         = [];
9✔
553
        $this->ignored         = [];
9✔
554
        $this->reportFile      = null;
9✔
555
        $this->generator       = null;
9✔
556
        $this->filter          = null;
9✔
557
        $this->bootstrap       = [];
9✔
558
        $this->basepath        = null;
9✔
559
        $this->reports         = ['full' => null];
9✔
560
        $this->reportWidth     = 'auto';
9✔
561
        $this->errorSeverity   = 5;
9✔
562
        $this->warningSeverity = 5;
9✔
563
        $this->recordErrors    = true;
9✔
564
        $this->suffix          = '';
9✔
565
        $this->stdin           = false;
9✔
566
        $this->stdinContent    = null;
9✔
567
        $this->stdinPath       = null;
9✔
568
        $this->trackTime       = false;
9✔
569
        $this->unknown         = [];
9✔
570

571
        $standard = self::getConfigData('default_standard');
9✔
572
        if ($standard !== null) {
9✔
573
            $this->standards = explode(',', $standard);
6✔
574
        }
2✔
575

576
        $reportFormat = self::getConfigData('report_format');
9✔
577
        if ($reportFormat !== null) {
9✔
578
            $this->reports = [$reportFormat => null];
×
579
        }
580

581
        $tabWidth = self::getConfigData('tab_width');
9✔
582
        if ($tabWidth !== null) {
9✔
583
            $this->tabWidth = (int) $tabWidth;
×
584
        }
585

586
        $encoding = self::getConfigData('encoding');
9✔
587
        if ($encoding !== null) {
9✔
588
            $this->encoding = strtolower($encoding);
×
589
        }
590

591
        $severity = self::getConfigData('severity');
9✔
592
        if ($severity !== null) {
9✔
593
            $this->errorSeverity   = (int) $severity;
×
594
            $this->warningSeverity = (int) $severity;
×
595
        }
596

597
        $severity = self::getConfigData('error_severity');
9✔
598
        if ($severity !== null) {
9✔
599
            $this->errorSeverity = (int) $severity;
×
600
        }
601

602
        $severity = self::getConfigData('warning_severity');
9✔
603
        if ($severity !== null) {
9✔
604
            $this->warningSeverity = (int) $severity;
×
605
        }
606

607
        $showWarnings = self::getConfigData('show_warnings');
9✔
608
        if ($showWarnings !== null) {
9✔
609
            $showWarnings = (bool) $showWarnings;
3✔
610
            if ($showWarnings === false) {
3✔
611
                $this->warningSeverity = 0;
3✔
612
            }
1✔
613
        }
1✔
614

615
        $reportWidth = self::getConfigData('report_width');
9✔
616
        if ($reportWidth !== null) {
9✔
617
            $this->reportWidth = $reportWidth;
3✔
618
        }
1✔
619

620
        $showProgress = self::getConfigData('show_progress');
9✔
621
        if ($showProgress !== null) {
9✔
622
            $this->showProgress = (bool) $showProgress;
×
623
        }
624

625
        $quiet = self::getConfigData('quiet');
9✔
626
        if ($quiet !== null) {
9✔
627
            $this->quiet = (bool) $quiet;
×
628
        }
629

630
        $colors = self::getConfigData('colors');
9✔
631
        if ($colors !== null) {
9✔
632
            $this->colors = (bool) $colors;
×
633
        }
634

635
        if (defined('PHP_CODESNIFFER_IN_TESTS') === false) {
9✔
636
            $cache = self::getConfigData('cache');
×
637
            if ($cache !== null) {
×
638
                $this->cache = (bool) $cache;
×
639
            }
640

641
            $parallel = self::getConfigData('parallel');
×
642
            if ($parallel !== null) {
×
643
                $this->parallel = max((int) $parallel, 1);
×
644
            }
645
        }
646

647
    }//end restoreDefaults()
6✔
648

649

650
    /**
651
     * Processes a short (-e) command line argument.
652
     *
653
     * @param string $arg The command line argument.
654
     * @param int    $pos The position of the argument on the command line.
655
     *
656
     * @return void
657
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
658
     */
659
    public function processShortArgument($arg, $pos)
×
660
    {
661
        switch ($arg) {
662
        case 'h':
×
663
        case '?':
×
664
            ob_start();
×
665
            $this->printUsage();
×
666
            $output = ob_get_contents();
×
667
            ob_end_clean();
×
668
            throw new DeepExitException($output, 0);
×
669
        case 'i' :
×
670
            ob_start();
×
671
            Standards::printInstalledStandards();
×
672
            $output = ob_get_contents();
×
673
            ob_end_clean();
×
674
            throw new DeepExitException($output, 0);
×
675
        case 'v' :
×
676
            if ($this->quiet === true) {
×
677
                // Ignore when quiet mode is enabled.
678
                break;
×
679
            }
680

681
            $this->verbosity++;
×
682
            self::$overriddenDefaults['verbosity'] = true;
×
683
            break;
×
684
        case 'l' :
×
685
            $this->local = true;
×
686
            self::$overriddenDefaults['local'] = true;
×
687
            break;
×
688
        case 's' :
×
689
            $this->showSources = true;
×
690
            self::$overriddenDefaults['showSources'] = true;
×
691
            break;
×
692
        case 'a' :
×
693
            $this->interactive = true;
×
694
            self::$overriddenDefaults['interactive'] = true;
×
695
            break;
×
696
        case 'e':
×
697
            $this->explain = true;
×
698
            self::$overriddenDefaults['explain'] = true;
×
699
            break;
×
700
        case 'p' :
×
701
            if ($this->quiet === true) {
×
702
                // Ignore when quiet mode is enabled.
703
                break;
×
704
            }
705

706
            $this->showProgress = true;
×
707
            self::$overriddenDefaults['showProgress'] = true;
×
708
            break;
×
709
        case 'q' :
×
710
            // Quiet mode disables a few other settings as well.
711
            $this->quiet        = true;
×
712
            $this->showProgress = false;
×
713
            $this->verbosity    = 0;
×
714

715
            self::$overriddenDefaults['quiet'] = true;
×
716
            break;
×
717
        case 'm' :
×
718
            $this->recordErrors = false;
×
719
            self::$overriddenDefaults['recordErrors'] = true;
×
720
            break;
×
721
        case 'd' :
×
722
            $ini = explode('=', $this->cliArgs[($pos + 1)]);
×
723
            $this->cliArgs[($pos + 1)] = '';
×
724
            if (isset($ini[1]) === true) {
×
725
                ini_set($ini[0], $ini[1]);
×
726
            } else {
727
                ini_set($ini[0], true);
×
728
            }
729
            break;
×
730
        case 'n' :
×
731
            if (isset(self::$overriddenDefaults['warningSeverity']) === false) {
×
732
                $this->warningSeverity = 0;
×
733
                self::$overriddenDefaults['warningSeverity'] = true;
×
734
            }
735
            break;
×
736
        case 'w' :
×
737
            if (isset(self::$overriddenDefaults['warningSeverity']) === false) {
×
738
                $this->warningSeverity = $this->errorSeverity;
×
739
                self::$overriddenDefaults['warningSeverity'] = true;
×
740
            }
741
            break;
×
742
        default:
743
            if ($this->dieOnUnknownArg === false) {
×
744
                $unknown       = $this->unknown;
×
745
                $unknown[]     = $arg;
×
746
                $this->unknown = $unknown;
×
747
            } else {
748
                $this->processUnknownArgument('-'.$arg, $pos);
×
749
            }
750
        }//end switch
751

752
    }//end processShortArgument()
753

754

755
    /**
756
     * Processes a long (--example) command-line argument.
757
     *
758
     * @param string $arg The command line argument.
759
     * @param int    $pos The position of the argument on the command line.
760
     *
761
     * @return void
762
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
763
     */
764
    public function processLongArgument($arg, $pos)
153✔
765
    {
766
        switch ($arg) {
51✔
767
        case 'help':
153✔
768
            ob_start();
×
769
            $this->printUsage();
×
770
            $output = ob_get_contents();
×
771
            ob_end_clean();
×
772
            throw new DeepExitException($output, 0);
×
773
        case 'version':
153✔
774
            $output  = 'PHP_CodeSniffer version '.self::VERSION.' ('.self::STABILITY.') ';
×
775
            $output .= 'by Squiz and PHPCSStandards'.PHP_EOL;
×
776
            throw new DeepExitException($output, 0);
×
777
        case 'colors':
153✔
778
            if (isset(self::$overriddenDefaults['colors']) === true) {
×
779
                break;
×
780
            }
781

782
            $this->colors = true;
×
783
            self::$overriddenDefaults['colors'] = true;
×
784
            break;
×
785
        case 'no-colors':
153✔
786
            if (isset(self::$overriddenDefaults['colors']) === true) {
×
787
                break;
×
788
            }
789

790
            $this->colors = false;
×
791
            self::$overriddenDefaults['colors'] = true;
×
792
            break;
×
793
        case 'cache':
153✔
794
            if (isset(self::$overriddenDefaults['cache']) === true) {
×
795
                break;
×
796
            }
797

798
            if (defined('PHP_CODESNIFFER_IN_TESTS') === false) {
×
799
                $this->cache = true;
×
800
                self::$overriddenDefaults['cache'] = true;
×
801
            }
802
            break;
×
803
        case 'no-cache':
153✔
804
            if (isset(self::$overriddenDefaults['cache']) === true) {
×
805
                break;
×
806
            }
807

808
            $this->cache = false;
×
809
            self::$overriddenDefaults['cache'] = true;
×
810
            break;
×
811
        case 'ignore-annotations':
153✔
812
            if (isset(self::$overriddenDefaults['annotations']) === true) {
×
813
                break;
×
814
            }
815

816
            $this->annotations = false;
×
817
            self::$overriddenDefaults['annotations'] = true;
×
818
            break;
×
819
        case 'config-set':
153✔
820
            if (isset($this->cliArgs[($pos + 1)]) === false
×
821
                || isset($this->cliArgs[($pos + 2)]) === false
×
822
            ) {
823
                $error  = 'ERROR: Setting a config option requires a name and value'.PHP_EOL.PHP_EOL;
×
824
                $error .= $this->printShortUsage(true);
×
825
                throw new DeepExitException($error, 3);
×
826
            }
827

828
            $key     = $this->cliArgs[($pos + 1)];
×
829
            $value   = $this->cliArgs[($pos + 2)];
×
830
            $current = self::getConfigData($key);
×
831

832
            try {
833
                $this->setConfigData($key, $value);
×
834
            } catch (Exception $e) {
×
835
                throw new DeepExitException($e->getMessage().PHP_EOL, 3);
×
836
            }
837

838
            $output = 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL;
×
839

840
            if ($current === null) {
×
841
                $output .= "Config value \"$key\" added successfully".PHP_EOL;
×
842
            } else {
843
                $output .= "Config value \"$key\" updated successfully; old value was \"$current\"".PHP_EOL;
×
844
            }
845
            throw new DeepExitException($output, 0);
×
846
        case 'config-delete':
153✔
847
            if (isset($this->cliArgs[($pos + 1)]) === false) {
×
848
                $error  = 'ERROR: Deleting a config option requires the name of the option'.PHP_EOL.PHP_EOL;
×
849
                $error .= $this->printShortUsage(true);
×
850
                throw new DeepExitException($error, 3);
×
851
            }
852

853
            $output = 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL;
×
854

855
            $key     = $this->cliArgs[($pos + 1)];
×
856
            $current = self::getConfigData($key);
×
857
            if ($current === null) {
×
858
                $output .= "Config value \"$key\" has not been set".PHP_EOL;
×
859
            } else {
860
                try {
861
                    $this->setConfigData($key, null);
×
862
                } catch (Exception $e) {
×
863
                    throw new DeepExitException($e->getMessage().PHP_EOL, 3);
×
864
                }
865

866
                $output .= "Config value \"$key\" removed successfully; old value was \"$current\"".PHP_EOL;
×
867
            }
868
            throw new DeepExitException($output, 0);
×
869
        case 'config-show':
153✔
870
            ob_start();
×
871
            $data = self::getAllConfigData();
×
872
            echo 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL;
×
873
            $this->printConfigData($data);
×
874
            $output = ob_get_contents();
×
875
            ob_end_clean();
×
876
            throw new DeepExitException($output, 0);
×
877
        case 'runtime-set':
153✔
878
            if (isset($this->cliArgs[($pos + 1)]) === false
×
879
                || isset($this->cliArgs[($pos + 2)]) === false
×
880
            ) {
881
                $error  = 'ERROR: Setting a runtime config option requires a name and value'.PHP_EOL.PHP_EOL;
×
882
                $error .= $this->printShortUsage(true);
×
883
                throw new DeepExitException($error, 3);
×
884
            }
885

886
            $key   = $this->cliArgs[($pos + 1)];
×
887
            $value = $this->cliArgs[($pos + 2)];
×
888
            $this->cliArgs[($pos + 1)] = '';
×
889
            $this->cliArgs[($pos + 2)] = '';
×
890
            self::setConfigData($key, $value, true);
×
891
            if (isset(self::$overriddenDefaults['runtime-set']) === false) {
×
892
                self::$overriddenDefaults['runtime-set'] = [];
×
893
            }
894

895
            self::$overriddenDefaults['runtime-set'][$key] = true;
×
896
            break;
×
897
        default:
51✔
898
            if (substr($arg, 0, 7) === 'sniffs=') {
153✔
899
                if (isset(self::$overriddenDefaults['sniffs']) === true) {
57✔
900
                    break;
3✔
901
                }
902

903
                $this->sniffs = $this->parseSniffCodes(substr($arg, 7), 'sniffs');
57✔
904
                self::$overriddenDefaults['sniffs'] = true;
21✔
905
            } else if (substr($arg, 0, 8) === 'exclude=') {
103✔
906
                if (isset(self::$overriddenDefaults['exclude']) === true) {
57✔
907
                    break;
3✔
908
                }
909

910
                $this->exclude = $this->parseSniffCodes(substr($arg, 8), 'exclude');
57✔
911
                self::$overriddenDefaults['exclude'] = true;
21✔
912
            } else if (defined('PHP_CODESNIFFER_IN_TESTS') === false
46✔
913
                && substr($arg, 0, 6) === 'cache='
39✔
914
            ) {
13✔
915
                if ((isset(self::$overriddenDefaults['cache']) === true
×
916
                    && $this->cache === false)
×
917
                    || isset(self::$overriddenDefaults['cacheFile']) === true
×
918
                ) {
919
                    break;
×
920
                }
921

922
                // Turn caching on.
923
                $this->cache = true;
×
924
                self::$overriddenDefaults['cache'] = true;
×
925

926
                $this->cacheFile = Common::realpath(substr($arg, 6));
×
927

928
                // It may not exist and return false instead.
929
                if ($this->cacheFile === false) {
×
930
                    $this->cacheFile = substr($arg, 6);
×
931

932
                    $dir = dirname($this->cacheFile);
×
933
                    if (is_dir($dir) === false) {
×
934
                        $error  = 'ERROR: The specified cache file path "'.$this->cacheFile.'" points to a non-existent directory'.PHP_EOL.PHP_EOL;
×
935
                        $error .= $this->printShortUsage(true);
×
936
                        throw new DeepExitException($error, 3);
×
937
                    }
938

939
                    if ($dir === '.') {
×
940
                        // Passed cache file is a file in the current directory.
941
                        $this->cacheFile = getcwd().'/'.basename($this->cacheFile);
×
942
                    } else {
943
                        if ($dir[0] === '/') {
×
944
                            // An absolute path.
945
                            $dir = Common::realpath($dir);
×
946
                        } else {
947
                            $dir = Common::realpath(getcwd().'/'.$dir);
×
948
                        }
949

950
                        if ($dir !== false) {
×
951
                            // Cache file path is relative.
952
                            $this->cacheFile = $dir.'/'.basename($this->cacheFile);
×
953
                        }
954
                    }
955
                }//end if
956

957
                self::$overriddenDefaults['cacheFile'] = true;
×
958

959
                if (is_dir($this->cacheFile) === true) {
×
960
                    $error  = 'ERROR: The specified cache file path "'.$this->cacheFile.'" is a directory'.PHP_EOL.PHP_EOL;
×
961
                    $error .= $this->printShortUsage(true);
×
962
                    throw new DeepExitException($error, 3);
×
963
                }
964
            } else if (substr($arg, 0, 10) === 'bootstrap=') {
39✔
965
                $files     = explode(',', substr($arg, 10));
×
966
                $bootstrap = [];
×
967
                foreach ($files as $file) {
×
968
                    $path = Common::realpath($file);
×
969
                    if ($path === false) {
×
970
                        $error  = 'ERROR: The specified bootstrap file "'.$file.'" does not exist'.PHP_EOL.PHP_EOL;
×
971
                        $error .= $this->printShortUsage(true);
×
972
                        throw new DeepExitException($error, 3);
×
973
                    }
974

975
                    $bootstrap[] = $path;
×
976
                }
977

978
                $this->bootstrap = array_merge($this->bootstrap, $bootstrap);
×
979
                self::$overriddenDefaults['bootstrap'] = true;
×
980
            } else if (substr($arg, 0, 10) === 'file-list=') {
39✔
981
                $fileList = substr($arg, 10);
×
982
                $path     = Common::realpath($fileList);
×
983
                if ($path === false) {
×
984
                    $error  = 'ERROR: The specified file list "'.$fileList.'" does not exist'.PHP_EOL.PHP_EOL;
×
985
                    $error .= $this->printShortUsage(true);
×
986
                    throw new DeepExitException($error, 3);
×
987
                }
988

989
                $files = file($path);
×
990
                foreach ($files as $inputFile) {
×
991
                    $inputFile = trim($inputFile);
×
992

993
                    // Skip empty lines.
994
                    if ($inputFile === '') {
×
995
                        continue;
×
996
                    }
997

998
                    $this->processFilePath($inputFile);
×
999
                }
1000
            } else if (substr($arg, 0, 11) === 'stdin-path=') {
39✔
1001
                if (isset(self::$overriddenDefaults['stdinPath']) === true) {
×
1002
                    break;
×
1003
                }
1004

1005
                $this->stdinPath = Common::realpath(substr($arg, 11));
×
1006

1007
                // It may not exist and return false instead, so use whatever they gave us.
1008
                if ($this->stdinPath === false) {
×
1009
                    $this->stdinPath = trim(substr($arg, 11));
×
1010
                }
1011

1012
                self::$overriddenDefaults['stdinPath'] = true;
×
1013
            } else if (PHP_CODESNIFFER_CBF === false && substr($arg, 0, 12) === 'report-file=') {
39✔
1014
                if (isset(self::$overriddenDefaults['reportFile']) === true) {
×
1015
                    break;
×
1016
                }
1017

1018
                $this->reportFile = Common::realpath(substr($arg, 12));
×
1019

1020
                // It may not exist and return false instead.
1021
                if ($this->reportFile === false) {
×
1022
                    $this->reportFile = substr($arg, 12);
×
1023

1024
                    $dir = Common::realpath(dirname($this->reportFile));
×
1025
                    if (is_dir($dir) === false) {
×
1026
                        $error  = 'ERROR: The specified report file path "'.$this->reportFile.'" points to a non-existent directory'.PHP_EOL.PHP_EOL;
×
1027
                        $error .= $this->printShortUsage(true);
×
1028
                        throw new DeepExitException($error, 3);
×
1029
                    }
1030

1031
                    $this->reportFile = $dir.'/'.basename($this->reportFile);
×
1032
                }//end if
1033

1034
                self::$overriddenDefaults['reportFile'] = true;
×
1035

1036
                if (is_dir($this->reportFile) === true) {
×
1037
                    $error  = 'ERROR: The specified report file path "'.$this->reportFile.'" is a directory'.PHP_EOL.PHP_EOL;
×
1038
                    $error .= $this->printShortUsage(true);
×
1039
                    throw new DeepExitException($error, 3);
×
1040
                }
1041
            } else if (substr($arg, 0, 13) === 'report-width=') {
39✔
1042
                if (isset(self::$overriddenDefaults['reportWidth']) === true) {
9✔
1043
                    break;
3✔
1044
                }
1045

1046
                $this->reportWidth = substr($arg, 13);
9✔
1047
                self::$overriddenDefaults['reportWidth'] = true;
9✔
1048
            } else if (substr($arg, 0, 9) === 'basepath=') {
33✔
1049
                if (isset(self::$overriddenDefaults['basepath']) === true) {
×
1050
                    break;
×
1051
                }
1052

1053
                self::$overriddenDefaults['basepath'] = true;
×
1054

1055
                if (substr($arg, 9) === '') {
×
1056
                    $this->basepath = null;
×
1057
                    break;
×
1058
                }
1059

1060
                $this->basepath = Common::realpath(substr($arg, 9));
×
1061

1062
                // It may not exist and return false instead.
1063
                if ($this->basepath === false) {
×
1064
                    $this->basepath = substr($arg, 9);
×
1065
                }
1066

1067
                if (is_dir($this->basepath) === false) {
×
1068
                    $error  = 'ERROR: The specified basepath "'.$this->basepath.'" points to a non-existent directory'.PHP_EOL.PHP_EOL;
×
1069
                    $error .= $this->printShortUsage(true);
×
1070
                    throw new DeepExitException($error, 3);
×
1071
                }
1072
            } else if ((substr($arg, 0, 7) === 'report=' || substr($arg, 0, 7) === 'report-')) {
30✔
1073
                $reports = [];
×
1074

1075
                if ($arg[6] === '-') {
×
1076
                    // This is a report with file output.
1077
                    $split = strpos($arg, '=');
×
1078
                    if ($split === false) {
×
1079
                        $report = substr($arg, 7);
×
1080
                        $output = null;
×
1081
                    } else {
1082
                        $report = substr($arg, 7, ($split - 7));
×
1083
                        $output = substr($arg, ($split + 1));
×
1084
                        if ($output === false) {
×
1085
                            $output = null;
×
1086
                        } else {
1087
                            $dir = Common::realpath(dirname($output));
×
1088
                            if (is_dir($dir) === false) {
×
1089
                                $error  = 'ERROR: The specified '.$report.' report file path "'.$output.'" points to a non-existent directory'.PHP_EOL.PHP_EOL;
×
1090
                                $error .= $this->printShortUsage(true);
×
1091
                                throw new DeepExitException($error, 3);
×
1092
                            }
1093

1094
                            $output = $dir.'/'.basename($output);
×
1095

1096
                            if (is_dir($output) === true) {
×
1097
                                $error  = 'ERROR: The specified '.$report.' report file path "'.$output.'" is a directory'.PHP_EOL.PHP_EOL;
×
1098
                                $error .= $this->printShortUsage(true);
×
1099
                                throw new DeepExitException($error, 3);
×
1100
                            }
1101
                        }//end if
1102
                    }//end if
1103

1104
                    $reports[$report] = $output;
×
1105
                } else {
1106
                    // This is a single report.
1107
                    if (isset(self::$overriddenDefaults['reports']) === true) {
×
1108
                        break;
×
1109
                    }
1110

1111
                    $reportNames = explode(',', substr($arg, 7));
×
1112
                    foreach ($reportNames as $report) {
×
1113
                        $reports[$report] = null;
×
1114
                    }
1115
                }//end if
1116

1117
                // Remove the default value so the CLI value overrides it.
1118
                if (isset(self::$overriddenDefaults['reports']) === false) {
×
1119
                    $this->reports = $reports;
×
1120
                } else {
1121
                    $this->reports = array_merge($this->reports, $reports);
×
1122
                }
1123

1124
                self::$overriddenDefaults['reports'] = true;
×
1125
            } else if (substr($arg, 0, 7) === 'filter=') {
30✔
1126
                if (isset(self::$overriddenDefaults['filter']) === true) {
×
1127
                    break;
×
1128
                }
1129

1130
                $this->filter = substr($arg, 7);
×
1131
                self::$overriddenDefaults['filter'] = true;
×
1132
            } else if (substr($arg, 0, 9) === 'standard=') {
30✔
1133
                $standards = trim(substr($arg, 9));
×
1134
                if ($standards !== '') {
×
1135
                    $this->standards = explode(',', $standards);
×
1136
                }
1137

1138
                self::$overriddenDefaults['standards'] = true;
×
1139
            } else if (substr($arg, 0, 11) === 'extensions=') {
30✔
1140
                if (isset(self::$overriddenDefaults['extensions']) === true) {
×
1141
                    break;
×
1142
                }
1143

1144
                $extensions    = explode(',', substr($arg, 11));
×
1145
                $newExtensions = [];
×
1146
                foreach ($extensions as $ext) {
×
1147
                    $slash = strpos($ext, '/');
×
1148
                    if ($slash !== false) {
×
1149
                        // They specified the tokenizer too.
1150
                        list($ext, $tokenizer) = explode('/', $ext);
×
1151
                        $newExtensions[$ext]   = strtoupper($tokenizer);
×
1152
                        continue;
×
1153
                    }
1154

1155
                    if (isset($this->extensions[$ext]) === true) {
×
1156
                        $newExtensions[$ext] = $this->extensions[$ext];
×
1157
                    } else {
1158
                        $newExtensions[$ext] = 'PHP';
×
1159
                    }
1160
                }
1161

1162
                $this->extensions = $newExtensions;
×
1163
                self::$overriddenDefaults['extensions'] = true;
×
1164
            } else if (substr($arg, 0, 7) === 'suffix=') {
30✔
1165
                if (isset(self::$overriddenDefaults['suffix']) === true) {
×
1166
                    break;
×
1167
                }
1168

1169
                $this->suffix = substr($arg, 7);
×
1170
                self::$overriddenDefaults['suffix'] = true;
×
1171
            } else if (substr($arg, 0, 9) === 'parallel=') {
30✔
1172
                if (isset(self::$overriddenDefaults['parallel']) === true) {
×
1173
                    break;
×
1174
                }
1175

1176
                $this->parallel = max((int) substr($arg, 9), 1);
×
1177
                self::$overriddenDefaults['parallel'] = true;
×
1178
            } else if (substr($arg, 0, 9) === 'severity=') {
30✔
1179
                $this->errorSeverity   = (int) substr($arg, 9);
×
1180
                $this->warningSeverity = $this->errorSeverity;
×
1181
                if (isset(self::$overriddenDefaults['errorSeverity']) === false) {
×
1182
                    self::$overriddenDefaults['errorSeverity'] = true;
×
1183
                }
1184

1185
                if (isset(self::$overriddenDefaults['warningSeverity']) === false) {
×
1186
                    self::$overriddenDefaults['warningSeverity'] = true;
×
1187
                }
1188
            } else if (substr($arg, 0, 15) === 'error-severity=') {
30✔
1189
                if (isset(self::$overriddenDefaults['errorSeverity']) === true) {
×
1190
                    break;
×
1191
                }
1192

1193
                $this->errorSeverity = (int) substr($arg, 15);
×
1194
                self::$overriddenDefaults['errorSeverity'] = true;
×
1195
            } else if (substr($arg, 0, 17) === 'warning-severity=') {
30✔
1196
                if (isset(self::$overriddenDefaults['warningSeverity']) === true) {
×
1197
                    break;
×
1198
                }
1199

1200
                $this->warningSeverity = (int) substr($arg, 17);
×
1201
                self::$overriddenDefaults['warningSeverity'] = true;
×
1202
            } else if (substr($arg, 0, 7) === 'ignore=') {
30✔
1203
                if (isset(self::$overriddenDefaults['ignored']) === true) {
×
1204
                    break;
×
1205
                }
1206

1207
                // Split the ignore string on commas, unless the comma is escaped
1208
                // using 1 or 3 slashes (\, or \\\,).
1209
                $patterns = preg_split(
×
1210
                    '/(?<=(?<!\\\\)\\\\\\\\),|(?<!\\\\),/',
×
1211
                    substr($arg, 7)
×
1212
                );
1213

1214
                $ignored = [];
×
1215
                foreach ($patterns as $pattern) {
×
1216
                    $pattern = trim($pattern);
×
1217
                    if ($pattern === '') {
×
1218
                        continue;
×
1219
                    }
1220

1221
                    $ignored[$pattern] = 'absolute';
×
1222
                }
1223

1224
                $this->ignored = $ignored;
×
1225
                self::$overriddenDefaults['ignored'] = true;
×
1226
            } else if (substr($arg, 0, 10) === 'generator='
30✔
1227
                && PHP_CODESNIFFER_CBF === false
30✔
1228
            ) {
10✔
1229
                if (isset(self::$overriddenDefaults['generator']) === true) {
30✔
1230
                    break;
3✔
1231
                }
1232

1233
                $generatorName          = substr($arg, 10);
30✔
1234
                $lowerCaseGeneratorName = strtolower($generatorName);
30✔
1235

1236
                if (isset($this->validGenerators[$lowerCaseGeneratorName]) === false) {
30✔
1237
                    $validOptions = implode(', ', $this->validGenerators);
9✔
1238
                    $validOptions = substr_replace($validOptions, ' and', strrpos($validOptions, ','), 1);
9✔
1239
                    $error        = sprintf(
9✔
1240
                        'ERROR: "%s" is not a valid generator. The following generators are supported: %s.'.PHP_EOL.PHP_EOL,
9✔
1241
                        $generatorName,
9✔
1242
                        $validOptions
6✔
1243
                    );
6✔
1244
                    $error       .= $this->printShortUsage(true);
9✔
1245
                    throw new DeepExitException($error, 3);
9✔
1246
                }
1247

1248
                $this->generator = $this->validGenerators[$lowerCaseGeneratorName];
21✔
1249
                self::$overriddenDefaults['generator'] = true;
21✔
1250
            } else if (substr($arg, 0, 9) === 'encoding=') {
7✔
1251
                if (isset(self::$overriddenDefaults['encoding']) === true) {
×
1252
                    break;
×
1253
                }
1254

1255
                $this->encoding = strtolower(substr($arg, 9));
×
1256
                self::$overriddenDefaults['encoding'] = true;
×
1257
            } else if (substr($arg, 0, 10) === 'tab-width=') {
×
1258
                if (isset(self::$overriddenDefaults['tabWidth']) === true) {
×
1259
                    break;
×
1260
                }
1261

1262
                $this->tabWidth = (int) substr($arg, 10);
×
1263
                self::$overriddenDefaults['tabWidth'] = true;
×
1264
            } else {
1265
                if ($this->dieOnUnknownArg === false) {
×
1266
                    $eqPos = strpos($arg, '=');
×
1267
                    try {
1268
                        $unknown = $this->unknown;
×
1269

1270
                        if ($eqPos === false) {
×
1271
                            $unknown[$arg] = $arg;
×
1272
                        } else {
1273
                            $value         = substr($arg, ($eqPos + 1));
×
1274
                            $arg           = substr($arg, 0, $eqPos);
×
1275
                            $unknown[$arg] = $value;
×
1276
                        }
1277

1278
                        $this->unknown = $unknown;
×
1279
                    } catch (RuntimeException $e) {
×
1280
                        // Value is not valid, so just ignore it.
1281
                    }
1282
                } else {
1283
                    $this->processUnknownArgument('--'.$arg, $pos);
×
1284
                }
1285
            }//end if
1286
            break;
72✔
1287
        }//end switch
51✔
1288

1289
    }//end processLongArgument()
48✔
1290

1291

1292
    /**
1293
     * Parse supplied string into a list of validated sniff codes.
1294
     *
1295
     * @param string $input    Comma-separated string of sniff codes.
1296
     * @param string $argument The name of the argument which is being processed.
1297
     *
1298
     * @return array<string>
1299
     * @throws DeepExitException When any of the provided codes are not valid as sniff codes.
1300
     */
1301
    private function parseSniffCodes($input, $argument)
114✔
1302
    {
1303
        $errors = [];
114✔
1304
        $sniffs = [];
114✔
1305

1306
        $possibleSniffs = array_filter(explode(',', $input));
114✔
1307

1308
        if ($possibleSniffs === []) {
114✔
1309
            $errors[] = 'No codes specified / empty argument';
18✔
1310
        }
6✔
1311

1312
        foreach ($possibleSniffs as $sniff) {
114✔
1313
            $sniff = trim($sniff);
96✔
1314

1315
            $partCount = substr_count($sniff, '.');
96✔
1316
            if ($partCount === 2) {
96✔
1317
                // Correct number of parts.
1318
                $sniffs[] = $sniff;
54✔
1319
                continue;
54✔
1320
            }
1321

1322
            if ($partCount === 0) {
54✔
1323
                $errors[] = 'Standard codes are not supported: '.$sniff;
12✔
1324
            } else if ($partCount === 1) {
46✔
1325
                $errors[] = 'Category codes are not supported: '.$sniff;
18✔
1326
            } else if ($partCount === 3) {
30✔
1327
                $errors[] = 'Message codes are not supported: '.$sniff;
18✔
1328
            } else {
6✔
1329
                $errors[] = 'Too many parts: '.$sniff;
12✔
1330
            }
1331

1332
            if ($partCount > 2) {
54✔
1333
                $parts    = explode('.', $sniff, 4);
24✔
1334
                $sniffs[] = $parts[0].'.'.$parts[1].'.'.$parts[2];
24✔
1335
            }
8✔
1336
        }//end foreach
38✔
1337

1338
        $sniffs = array_reduce(
114✔
1339
            $sniffs,
114✔
1340
            static function ($carry, $item) {
76✔
1341
                $lower = strtolower($item);
78✔
1342

1343
                foreach ($carry as $found) {
78✔
1344
                    if ($lower === strtolower($found)) {
36✔
1345
                        // This sniff is already in our list.
1346
                        return $carry;
24✔
1347
                    }
1348
                }
26✔
1349

1350
                $carry[] = $item;
78✔
1351

1352
                return $carry;
78✔
1353
            },
114✔
1354
            []
114✔
1355
        );
76✔
1356

1357
        if ($errors !== []) {
114✔
1358
            $error  = 'ERROR: The --'.$argument.' option only supports sniff codes.'.PHP_EOL;
72✔
1359
            $error .= 'Sniff codes are in the form "Standard.Category.Sniff".'.PHP_EOL;
72✔
1360
            $error .= PHP_EOL;
72✔
1361
            $error .= 'The following problems were detected:'.PHP_EOL;
72✔
1362
            $error .= '* '.implode(PHP_EOL.'* ', $errors).PHP_EOL;
72✔
1363

1364
            if ($sniffs !== []) {
72✔
1365
                $error .= PHP_EOL;
36✔
1366
                $error .= 'Perhaps try --'.$argument.'="'.implode(',', $sniffs).'" instead.'.PHP_EOL;
36✔
1367
            }
12✔
1368

1369
            $error .= PHP_EOL;
72✔
1370
            $error .= $this->printShortUsage(true);
72✔
1371
            throw new DeepExitException(ltrim($error), 3);
72✔
1372
        }
1373

1374
        return $sniffs;
42✔
1375

1376
    }//end parseSniffCodes()
1377

1378

1379
    /**
1380
     * Processes an unknown command line argument.
1381
     *
1382
     * Assumes all unknown arguments are files and folders to check.
1383
     *
1384
     * @param string $arg The command line argument.
1385
     * @param int    $pos The position of the argument on the command line.
1386
     *
1387
     * @return void
1388
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
1389
     */
1390
    public function processUnknownArgument($arg, $pos)
×
1391
    {
1392
        // We don't know about any additional switches; just files.
1393
        if ($arg[0] === '-') {
×
1394
            if ($this->dieOnUnknownArg === false) {
×
1395
                return;
×
1396
            }
1397

1398
            $error  = "ERROR: option \"$arg\" not known".PHP_EOL.PHP_EOL;
×
1399
            $error .= $this->printShortUsage(true);
×
1400
            throw new DeepExitException($error, 3);
×
1401
        }
1402

1403
        $this->processFilePath($arg);
×
1404

1405
    }//end processUnknownArgument()
1406

1407

1408
    /**
1409
     * Processes a file path and add it to the file list.
1410
     *
1411
     * @param string $path The path to the file to add.
1412
     *
1413
     * @return void
1414
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
1415
     */
1416
    public function processFilePath($path)
×
1417
    {
1418
        // If we are processing STDIN, don't record any files to check.
1419
        if ($this->stdin === true) {
×
1420
            return;
×
1421
        }
1422

1423
        $file = Common::realpath($path);
×
1424
        if (file_exists($file) === false) {
×
1425
            if ($this->dieOnUnknownArg === false) {
×
1426
                return;
×
1427
            }
1428

1429
            $error  = 'ERROR: The file "'.$path.'" does not exist.'.PHP_EOL.PHP_EOL;
×
1430
            $error .= $this->printShortUsage(true);
×
1431
            throw new DeepExitException($error, 3);
×
1432
        } else {
1433
            // Can't modify the files array directly because it's not a real
1434
            // class member, so need to use this little get/modify/set trick.
1435
            $files       = $this->files;
×
1436
            $files[]     = $file;
×
1437
            $this->files = $files;
×
1438
            self::$overriddenDefaults['files'] = true;
×
1439
        }
1440

1441
    }//end processFilePath()
1442

1443

1444
    /**
1445
     * Prints out the usage information for this script.
1446
     *
1447
     * @return void
1448
     */
1449
    public function printUsage()
×
1450
    {
1451
        echo PHP_EOL;
×
1452

1453
        if (PHP_CODESNIFFER_CBF === true) {
×
1454
            $this->printPHPCBFUsage();
×
1455
        } else {
1456
            $this->printPHPCSUsage();
×
1457
        }
1458

1459
        echo PHP_EOL;
×
1460

1461
    }//end printUsage()
1462

1463

1464
    /**
1465
     * Prints out the short usage information for this script.
1466
     *
1467
     * @param bool $return If TRUE, the usage string is returned
1468
     *                     instead of output to screen.
1469
     *
1470
     * @return string|void
1471
     */
1472
    public function printShortUsage($return=false)
×
1473
    {
1474
        if (PHP_CODESNIFFER_CBF === true) {
×
1475
            $usage = 'Run "phpcbf --help" for usage information';
×
1476
        } else {
1477
            $usage = 'Run "phpcs --help" for usage information';
×
1478
        }
1479

1480
        $usage .= PHP_EOL.PHP_EOL;
×
1481

1482
        if ($return === true) {
×
1483
            return $usage;
×
1484
        }
1485

1486
        echo $usage;
×
1487

1488
    }//end printShortUsage()
1489

1490

1491
    /**
1492
     * Prints out the usage information for PHPCS.
1493
     *
1494
     * @return void
1495
     */
1496
    public function printPHPCSUsage()
×
1497
    {
1498
        $longOptions   = explode(',', Help::DEFAULT_LONG_OPTIONS);
×
1499
        $longOptions[] = 'cache';
×
1500
        $longOptions[] = 'no-cache';
×
1501
        $longOptions[] = 'report';
×
1502
        $longOptions[] = 'report-file';
×
1503
        $longOptions[] = 'report-report';
×
1504
        $longOptions[] = 'config-explain';
×
1505
        $longOptions[] = 'config-set';
×
1506
        $longOptions[] = 'config-delete';
×
1507
        $longOptions[] = 'config-show';
×
1508
        $longOptions[] = 'generator';
×
1509

1510
        $shortOptions = Help::DEFAULT_SHORT_OPTIONS.'aems';
×
1511

1512
        (new Help($this, $longOptions, $shortOptions))->display();
×
1513

1514
    }//end printPHPCSUsage()
1515

1516

1517
    /**
1518
     * Prints out the usage information for PHPCBF.
1519
     *
1520
     * @return void
1521
     */
1522
    public function printPHPCBFUsage()
×
1523
    {
1524
        $longOptions   = explode(',', Help::DEFAULT_LONG_OPTIONS);
×
1525
        $longOptions[] = 'suffix';
×
1526
        $shortOptions  = Help::DEFAULT_SHORT_OPTIONS;
×
1527

1528
        (new Help($this, $longOptions, $shortOptions))->display();
×
1529

1530
    }//end printPHPCBFUsage()
1531

1532

1533
    /**
1534
     * Get a single config value.
1535
     *
1536
     * @param string $key The name of the config value.
1537
     *
1538
     * @return string|null
1539
     * @see    setConfigData()
1540
     * @see    getAllConfigData()
1541
     */
1542
    public static function getConfigData($key)
6✔
1543
    {
1544
        $phpCodeSnifferConfig = self::getAllConfigData();
6✔
1545

1546
        if ($phpCodeSnifferConfig === null) {
6✔
1547
            return null;
×
1548
        }
1549

1550
        if (isset($phpCodeSnifferConfig[$key]) === false) {
6✔
1551
            return null;
6✔
1552
        }
1553

1554
        return $phpCodeSnifferConfig[$key];
6✔
1555

1556
    }//end getConfigData()
1557

1558

1559
    /**
1560
     * Get the path to an executable utility.
1561
     *
1562
     * @param string $name The name of the executable utility.
1563
     *
1564
     * @return string|null
1565
     * @see    getConfigData()
1566
     */
1567
    public static function getExecutablePath($name)
4✔
1568
    {
1569
        $data = self::getConfigData($name.'_path');
4✔
1570
        if ($data !== null) {
4✔
1571
            return $data;
×
1572
        }
1573

1574
        if ($name === "php") {
4✔
1575
            // For php, we know the executable path. There's no need to look it up.
1576
            return PHP_BINARY;
×
1577
        }
1578

1579
        if (array_key_exists($name, self::$executablePaths) === true) {
4✔
1580
            return self::$executablePaths[$name];
2✔
1581
        }
1582

1583
        if (stripos(PHP_OS, 'WIN') === 0) {
4✔
1584
            $cmd = 'where '.escapeshellarg($name).' 2> nul';
2✔
1585
        } else {
1✔
1586
            $cmd = 'which '.escapeshellarg($name).' 2> /dev/null';
2✔
1587
        }
1588

1589
        $result = exec($cmd, $output, $retVal);
4✔
1590
        if ($retVal !== 0) {
4✔
1591
            $result = null;
×
1592
        }
1593

1594
        self::$executablePaths[$name] = $result;
4✔
1595
        return $result;
4✔
1596

1597
    }//end getExecutablePath()
1598

1599

1600
    /**
1601
     * Set a single config value.
1602
     *
1603
     * @param string      $key   The name of the config value.
1604
     * @param string|null $value The value to set. If null, the config
1605
     *                           entry is deleted, reverting it to the
1606
     *                           default value.
1607
     * @param boolean     $temp  Set this config data temporarily for this
1608
     *                           script run. This will not write the config
1609
     *                           data to the config file.
1610
     *
1611
     * @return bool
1612
     * @see    getConfigData()
1613
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the config file can not be written.
1614
     */
1615
    public static function setConfigData($key, $value, $temp=false)
×
1616
    {
1617
        if (isset(self::$overriddenDefaults['runtime-set']) === true
×
1618
            && isset(self::$overriddenDefaults['runtime-set'][$key]) === true
×
1619
        ) {
1620
            return false;
×
1621
        }
1622

1623
        if ($temp === false) {
×
1624
            $path = '';
×
1625
            if (is_callable('\Phar::running') === true) {
×
1626
                $path = Phar::running(false);
×
1627
            }
1628

1629
            if ($path !== '') {
×
1630
                $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1631
            } else {
1632
                $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1633
            }
1634

1635
            if (is_file($configFile) === true
×
1636
                && is_writable($configFile) === false
×
1637
            ) {
1638
                $error = 'ERROR: Config file '.$configFile.' is not writable'.PHP_EOL.PHP_EOL;
×
1639
                throw new DeepExitException($error, 3);
×
1640
            }
1641
        }//end if
1642

1643
        $phpCodeSnifferConfig = self::getAllConfigData();
×
1644

1645
        if ($value === null) {
×
1646
            if (isset($phpCodeSnifferConfig[$key]) === true) {
×
1647
                unset($phpCodeSnifferConfig[$key]);
×
1648
            }
1649
        } else {
1650
            $phpCodeSnifferConfig[$key] = $value;
×
1651
        }
1652

1653
        if ($temp === false) {
×
1654
            $output  = '<'.'?php'."\n".' $phpCodeSnifferConfig = ';
×
1655
            $output .= var_export($phpCodeSnifferConfig, true);
×
1656
            $output .= ";\n?".'>';
×
1657

1658
            if (file_put_contents($configFile, $output) === false) {
×
1659
                $error = 'ERROR: Config file '.$configFile.' could not be written'.PHP_EOL.PHP_EOL;
×
1660
                throw new DeepExitException($error, 3);
×
1661
            }
1662

1663
            self::$configDataFile = $configFile;
×
1664
        }
1665

1666
        self::$configData = $phpCodeSnifferConfig;
×
1667

1668
        // If the installed paths are being set, make sure all known
1669
        // standards paths are added to the autoloader.
1670
        if ($key === 'installed_paths') {
×
1671
            $installedStandards = Standards::getInstalledStandardDetails();
×
1672
            foreach ($installedStandards as $details) {
×
1673
                Autoload::addSearchPath($details['path'], $details['namespace']);
×
1674
            }
1675
        }
1676

1677
        return true;
×
1678

1679
    }//end setConfigData()
1680

1681

1682
    /**
1683
     * Get all config data.
1684
     *
1685
     * @return array<string, string>
1686
     * @see    getConfigData()
1687
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the config file could not be read.
1688
     */
1689
    public static function getAllConfigData()
×
1690
    {
1691
        if (self::$configData !== null) {
×
1692
            return self::$configData;
×
1693
        }
1694

1695
        $path = '';
×
1696
        if (is_callable('\Phar::running') === true) {
×
1697
            $path = Phar::running(false);
×
1698
        }
1699

1700
        if ($path !== '') {
×
1701
            $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1702
        } else {
1703
            $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1704
            if (is_file($configFile) === false
×
1705
                && strpos('@data_dir@', '@data_dir') === false
×
1706
            ) {
1707
                $configFile = '@data_dir@/PHP_CodeSniffer/CodeSniffer.conf';
×
1708
            }
1709
        }
1710

1711
        if (is_file($configFile) === false) {
×
1712
            self::$configData = [];
×
1713
            return [];
×
1714
        }
1715

1716
        if (Common::isReadable($configFile) === false) {
×
1717
            $error = 'ERROR: Config file '.$configFile.' is not readable'.PHP_EOL.PHP_EOL;
×
1718
            throw new DeepExitException($error, 3);
×
1719
        }
1720

1721
        include $configFile;
×
1722
        self::$configDataFile = $configFile;
×
1723
        self::$configData     = $phpCodeSnifferConfig;
×
1724
        return self::$configData;
×
1725

1726
    }//end getAllConfigData()
1727

1728

1729
    /**
1730
     * Prints out the gathered config data.
1731
     *
1732
     * @param array $data The config data to print.
1733
     *
1734
     * @return void
1735
     */
1736
    public function printConfigData($data)
×
1737
    {
1738
        $max  = 0;
×
1739
        $keys = array_keys($data);
×
1740
        foreach ($keys as $key) {
×
1741
            $len = strlen($key);
×
1742
            if (strlen($key) > $max) {
×
1743
                $max = $len;
×
1744
            }
1745
        }
1746

1747
        if ($max === 0) {
×
1748
            return;
×
1749
        }
1750

1751
        $max += 2;
×
1752
        ksort($data);
×
1753
        foreach ($data as $name => $value) {
×
1754
            echo str_pad($name.': ', $max).$value.PHP_EOL;
×
1755
        }
1756

1757
    }//end printConfigData()
1758

1759

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