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

PHPCSStandards / PHP_CodeSniffer / 14801234447

02 May 2025 06:39PM UTC coverage: 78.471% (+0.02%) from 78.454%
14801234447

push

github

web-flow
Merge pull request #1068 from PHPCSStandards/phpcs-4.0/feature/allow-testing-cache-option

Config: remove more test specific conditions

5 of 9 new or added lines in 1 file covered. (55.56%)

2 existing lines in 1 file now uncovered.

19566 of 24934 relevant lines covered (78.47%)

86.19 hits per line

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

36.84
/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 is used.
68
 *                                                  E.g., array('inc' => 'PHP');
69
 *                                                  Note: since PHPCS 4.0.0, the tokenizer used will always be 'PHP',
70
 *                                                  but the array format of the property has not been changed to prevent
71
 *                                                  breaking integrations which may be accessing this property.
72
 * @property array<string, string|null> $reports    The reports to use for printing output after the run.
73
 *                                                  The format of the array is:
74
 *                                                      array(
75
 *                                                          'reportName1' => 'outputFile',
76
 *                                                          'reportName2' => null,
77
 *                                                      );
78
 *                                                  If the array value is NULL, the report will be written to the screen.
79
 *
80
 * @property string[] $unknown Any arguments gathered on the command line that are unknown to us.
81
 *                             E.g., using `phpcs -c` will give array('c');
82
 */
83
class Config
84
{
85

86
    /**
87
     * The current version.
88
     *
89
     * @var string
90
     */
91
    public const VERSION = '4.0.0';
92

93
    /**
94
     * Package stability; either stable, beta or alpha.
95
     *
96
     * @var string
97
     */
98
    public const STABILITY = 'alpha';
99

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

107
    /**
108
     * Translation table for config settings which can be changed via multiple CLI flags.
109
     *
110
     * If the flag name matches the setting name, there is no need to add it to this translation table.
111
     * Similarly, if there is only one flag which can change a setting, there is no need to include
112
     * it in this table, even if the flag name and the setting name don't match.
113
     *
114
     * @var array<string, string> Key is the CLI flag name, value the corresponding config setting name.
115
     */
116
    public const CLI_FLAGS_TO_SETTING_NAME = [
117
        'n'                => 'warningSeverity',
118
        'w'                => 'warningSeverity',
119
        'warning-severity' => 'warningSeverity',
120
        'no-colors'        => 'colors',
121
        'no-cache'         => 'cache',
122
    ];
123

124
    /**
125
     * An array of settings that PHPCS and PHPCBF accept.
126
     *
127
     * This array is not meant to be accessed directly. Instead, use the settings
128
     * as if they are class member vars so the __get() and __set() magic methods
129
     * can be used to validate the values. For example, to set the verbosity level to
130
     * level 2, use $this->verbosity = 2; instead of accessing this property directly.
131
     *
132
     * Each of these settings is described in the class comment property list.
133
     *
134
     * @var array<string, mixed>
135
     */
136
    private $settings = [
137
        'files'           => null,
138
        'standards'       => null,
139
        'verbosity'       => null,
140
        'interactive'     => null,
141
        'parallel'        => null,
142
        'cache'           => null,
143
        'cacheFile'       => null,
144
        'colors'          => null,
145
        'explain'         => null,
146
        'local'           => null,
147
        'showSources'     => null,
148
        'showProgress'    => null,
149
        'quiet'           => null,
150
        'annotations'     => null,
151
        'tabWidth'        => null,
152
        'encoding'        => null,
153
        'extensions'      => null,
154
        'sniffs'          => null,
155
        'exclude'         => null,
156
        'ignored'         => null,
157
        'reportFile'      => null,
158
        'generator'       => null,
159
        'filter'          => null,
160
        'bootstrap'       => null,
161
        'reports'         => null,
162
        'basepath'        => null,
163
        'reportWidth'     => null,
164
        'errorSeverity'   => null,
165
        'warningSeverity' => null,
166
        'recordErrors'    => null,
167
        'suffix'          => null,
168
        'stdin'           => null,
169
        'stdinContent'    => null,
170
        'stdinPath'       => null,
171
        'trackTime'       => null,
172
        'unknown'         => null,
173
    ];
174

175
    /**
176
     * Whether or not to kill the process when an unknown command line arg is found.
177
     *
178
     * If FALSE, arguments that are not command line options or file/directory paths
179
     * will be ignored and execution will continue. These values will be stored in
180
     * $this->unknown.
181
     *
182
     * @var boolean
183
     */
184
    public $dieOnUnknownArg;
185

186
    /**
187
     * The current command line arguments we are processing.
188
     *
189
     * @var string[]
190
     */
191
    private $cliArgs = [];
192

193
    /**
194
     * A list of valid generators.
195
     *
196
     * {@internal Once support for PHP < 5.6 is dropped, this property should be refactored into a
197
     * class constant.}
198
     *
199
     * @var array<string, string> Keys are the lowercase version of the generator name, while values
200
     *                            are the associated PHP generator class.
201
     */
202
    private $validGenerators = [
203
        'text'     => 'Text',
204
        'html'     => 'HTML',
205
        'markdown' => 'Markdown',
206
    ];
207

208
    /**
209
     * Command line values that the user has supplied directly.
210
     *
211
     * @var array<string, true|array<string, true>>
212
     */
213
    private $overriddenDefaults = [];
214

215
    /**
216
     * Config file data that has been loaded for the run.
217
     *
218
     * @var array<string, string>
219
     */
220
    private static $configData = null;
221

222
    /**
223
     * The full path to the config data file that has been loaded.
224
     *
225
     * @var string
226
     */
227
    private static $configDataFile = null;
228

229
    /**
230
     * Automatically discovered executable utility paths.
231
     *
232
     * @var array<string, string>
233
     */
234
    private static $executablePaths = [];
235

236

237
    /**
238
     * Get the value of an inaccessible property.
239
     *
240
     * @param string $name The name of the property.
241
     *
242
     * @return mixed
243
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the setting name is invalid.
244
     */
245
    public function __get($name)
48✔
246
    {
247
        if (array_key_exists($name, $this->settings) === false) {
48✔
248
            throw new RuntimeException("ERROR: unable to get value of property \"$name\"");
×
249
        }
250

251
        // Figure out what the terminal width needs to be for "auto".
252
        if ($name === 'reportWidth' && $this->settings[$name] === 'auto') {
48✔
253
            if (function_exists('shell_exec') === true) {
9✔
254
                $dimensions = shell_exec('stty size 2>&1');
9✔
255
                if (is_string($dimensions) === true && preg_match('|\d+ (\d+)|', $dimensions, $matches) === 1) {
9✔
256
                    $this->settings[$name] = (int) $matches[1];
×
257
                }
258
            }
259

260
            if ($this->settings[$name] === 'auto') {
9✔
261
                // If shell_exec wasn't available or didn't yield a usable value, set to the default.
262
                // This will prevent subsequent retrievals of the reportWidth from making another call to stty.
263
                $this->settings[$name] = self::DEFAULT_REPORT_WIDTH;
9✔
264
            }
265
        }
266

267
        return $this->settings[$name];
48✔
268

269
    }//end __get()
270

271

272
    /**
273
     * Set the value of an inaccessible property.
274
     *
275
     * @param string $name  The name of the property.
276
     * @param mixed  $value The value of the property.
277
     *
278
     * @return void
279
     * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the setting name is invalid.
280
     */
281
    public function __set($name, $value)
48✔
282
    {
283
        if (array_key_exists($name, $this->settings) === false) {
48✔
284
            throw new RuntimeException("Can't __set() $name; setting doesn't exist");
×
285
        }
286

287
        switch ($name) {
16✔
288
        case 'reportWidth' :
48✔
289
            if (is_string($value) === true && $value === 'auto') {
48✔
290
                // Nothing to do. Leave at 'auto'.
291
                break;
48✔
292
            }
293

294
            if (is_int($value) === true) {
39✔
295
                $value = abs($value);
6✔
296
            } else if (is_string($value) === true && preg_match('`^\d+$`', $value) === 1) {
33✔
297
                $value = (int) $value;
15✔
298
            } else {
299
                $value = self::DEFAULT_REPORT_WIDTH;
18✔
300
            }
301
            break;
39✔
302

303
        case 'standards' :
48✔
304
            $cleaned = [];
48✔
305

306
            // Check if the standard name is valid, or if the case is invalid.
307
            $installedStandards = Standards::getInstalledStandards();
48✔
308
            foreach ($value as $standard) {
48✔
309
                foreach ($installedStandards as $validStandard) {
48✔
310
                    if (strtolower($standard) === strtolower($validStandard)) {
48✔
311
                        $standard = $validStandard;
48✔
312
                        break;
48✔
313
                    }
314
                }
315

316
                $cleaned[] = $standard;
48✔
317
            }
318

319
            $value = $cleaned;
48✔
320
            break;
48✔
321

322
        // Only track time when explicitly needed.
323
        case 'verbosity':
48✔
324
            if ($value > 2) {
48✔
325
                $this->settings['trackTime'] = true;
×
326
            }
327
            break;
48✔
328
        case 'reports':
48✔
329
            $reports = array_change_key_case($value, CASE_LOWER);
48✔
330
            if (array_key_exists('performance', $reports) === true) {
48✔
331
                $this->settings['trackTime'] = true;
×
332
            }
333
            break;
48✔
334

335
        default :
336
            // No validation required.
337
            break;
48✔
338
        }//end switch
339

340
        $this->settings[$name] = $value;
48✔
341

342
    }//end __set()
16✔
343

344

345
    /**
346
     * Check if the value of an inaccessible property is set.
347
     *
348
     * @param string $name The name of the property.
349
     *
350
     * @return bool
351
     */
352
    public function __isset($name)
×
353
    {
354
        return isset($this->settings[$name]);
×
355

356
    }//end __isset()
357

358

359
    /**
360
     * Unset the value of an inaccessible property.
361
     *
362
     * @param string $name The name of the property.
363
     *
364
     * @return void
365
     */
366
    public function __unset($name)
×
367
    {
368
        $this->settings[$name] = null;
×
369

370
    }//end __unset()
371

372

373
    /**
374
     * Get the array of all config settings.
375
     *
376
     * @return array<string, mixed>
377
     */
378
    public function getSettings()
×
379
    {
380
        return $this->settings;
×
381

382
    }//end getSettings()
383

384

385
    /**
386
     * Set the array of all config settings.
387
     *
388
     * @param array<string, mixed> $settings The array of config settings.
389
     *
390
     * @return void
391
     */
392
    public function setSettings($settings)
×
393
    {
394
        $this->settings = $settings;
×
395

396
    }//end setSettings()
397

398

399
    /**
400
     * Creates a Config object and populates it with command line values.
401
     *
402
     * @param array $cliArgs         An array of values gathered from CLI args.
403
     * @param bool  $dieOnUnknownArg Whether or not to kill the process when an
404
     *                               unknown command line arg is found.
405
     *
406
     * @return void
407
     */
408
    public function __construct(array $cliArgs=[], $dieOnUnknownArg=true)
×
409
    {
410
        if (defined('PHP_CODESNIFFER_IN_TESTS') === true) {
×
411
            // Let everything through during testing so that we can
412
            // make use of PHPUnit command line arguments as well.
413
            $this->dieOnUnknownArg = false;
×
414
        } else {
415
            $this->dieOnUnknownArg = $dieOnUnknownArg;
×
416
        }
417

418
        if (empty($cliArgs) === true) {
×
419
            $cliArgs = $_SERVER['argv'];
×
420
            array_shift($cliArgs);
×
421
        }
422

423
        $this->restoreDefaults();
×
424
        $this->setCommandLineValues($cliArgs);
×
425

426
        if (isset($this->overriddenDefaults['standards']) === false) {
×
427
            // They did not supply a standard to use.
428
            // Look for a default ruleset in the current directory or higher.
429
            $currentDir = getcwd();
×
430

431
            $defaultFiles = [
432
                '.phpcs.xml',
×
433
                'phpcs.xml',
434
                '.phpcs.xml.dist',
435
                'phpcs.xml.dist',
436
            ];
437

438
            do {
439
                foreach ($defaultFiles as $defaultFilename) {
×
440
                    $default = $currentDir.DIRECTORY_SEPARATOR.$defaultFilename;
×
441
                    if (is_file($default) === true) {
×
442
                        $this->standards = [$default];
×
443
                        break(2);
×
444
                    }
445
                }
446

447
                $lastDir    = $currentDir;
×
448
                $currentDir = dirname($currentDir);
×
449
            } while ($currentDir !== '.' && $currentDir !== $lastDir && Common::isReadable($currentDir) === true);
×
450
        }//end if
451

452
        if (defined('STDIN') === false
×
453
            || PHP_OS_FAMILY === 'Windows'
×
454
        ) {
455
            return;
×
456
        }
457

458
        $handle = fopen('php://stdin', 'r');
×
459

460
        // Check for content on STDIN.
461
        if ($this->stdin === true
×
462
            || (Common::isStdinATTY() === false
×
463
            && feof($handle) === false)
×
464
        ) {
465
            $readStreams = [$handle];
×
466
            $writeSteams = null;
×
467

468
            $fileContents = '';
×
469
            while (is_resource($handle) === true && feof($handle) === false) {
×
470
                // Set a timeout of 200ms.
471
                if (stream_select($readStreams, $writeSteams, $writeSteams, 0, 200000) === 0) {
×
472
                    break;
×
473
                }
474

475
                $fileContents .= fgets($handle);
×
476
            }
477

478
            if (trim($fileContents) !== '') {
×
479
                $this->stdin        = true;
×
480
                $this->stdinContent = $fileContents;
×
481
                $this->overriddenDefaults['stdin']        = true;
×
482
                $this->overriddenDefaults['stdinContent'] = true;
×
483
            }
484
        }//end if
485

486
        fclose($handle);
×
487

488
    }//end __construct()
489

490

491
    /**
492
     * Set the command line values.
493
     *
494
     * @param array $args An array of command line arguments to set.
495
     *
496
     * @return void
497
     */
498
    public function setCommandLineValues($args)
×
499
    {
500
        $this->cliArgs = $args;
×
501
        $numArgs       = count($args);
×
502

503
        for ($i = 0; $i < $numArgs; $i++) {
×
504
            $arg = $this->cliArgs[$i];
×
505
            if ($arg === '') {
×
506
                continue;
×
507
            }
508

509
            if ($arg[0] === '-') {
×
510
                if ($arg === '-') {
×
511
                    // Asking to read from STDIN.
512
                    $this->stdin = true;
×
513
                    $this->overriddenDefaults['stdin'] = true;
×
514
                    continue;
×
515
                }
516

517
                if ($arg === '--') {
×
518
                    // Empty argument, ignore it.
519
                    continue;
×
520
                }
521

522
                if ($arg[1] === '-') {
×
523
                    $this->processLongArgument(substr($arg, 2), $i);
×
524
                } else {
525
                    $switches = str_split($arg);
×
526
                    foreach ($switches as $switch) {
×
527
                        if ($switch === '-') {
×
528
                            continue;
×
529
                        }
530

531
                        $this->processShortArgument($switch, $i);
×
532
                    }
533
                }
534
            } else {
535
                $this->processUnknownArgument($arg, $i);
×
536
            }//end if
537
        }//end for
538

539
    }//end setCommandLineValues()
540

541

542
    /**
543
     * Restore default values for all possible command line arguments.
544
     *
545
     * @return void
546
     */
547
    public function restoreDefaults()
9✔
548
    {
549
        $this->files           = [];
9✔
550
        $this->standards       = ['PSR12'];
9✔
551
        $this->verbosity       = 0;
9✔
552
        $this->interactive     = false;
9✔
553
        $this->cache           = false;
9✔
554
        $this->cacheFile       = null;
9✔
555
        $this->colors          = false;
9✔
556
        $this->explain         = false;
9✔
557
        $this->local           = false;
9✔
558
        $this->showSources     = false;
9✔
559
        $this->showProgress    = false;
9✔
560
        $this->quiet           = false;
9✔
561
        $this->annotations     = true;
9✔
562
        $this->parallel        = 1;
9✔
563
        $this->tabWidth        = 0;
9✔
564
        $this->encoding        = 'utf-8';
9✔
565
        $this->extensions      = [
9✔
566
            'php' => 'PHP',
6✔
567
            'inc' => 'PHP',
6✔
568
        ];
6✔
569
        $this->sniffs          = [];
9✔
570
        $this->exclude         = [];
9✔
571
        $this->ignored         = [];
9✔
572
        $this->reportFile      = null;
9✔
573
        $this->generator       = null;
9✔
574
        $this->filter          = null;
9✔
575
        $this->bootstrap       = [];
9✔
576
        $this->basepath        = null;
9✔
577
        $this->reports         = ['full' => null];
9✔
578
        $this->reportWidth     = 'auto';
9✔
579
        $this->errorSeverity   = 5;
9✔
580
        $this->warningSeverity = 5;
9✔
581
        $this->recordErrors    = true;
9✔
582
        $this->suffix          = '';
9✔
583
        $this->stdin           = false;
9✔
584
        $this->stdinContent    = null;
9✔
585
        $this->stdinPath       = null;
9✔
586
        $this->trackTime       = false;
9✔
587
        $this->unknown         = [];
9✔
588

589
        $standard = self::getConfigData('default_standard');
9✔
590
        if ($standard !== null) {
9✔
591
            $this->standards = explode(',', $standard);
6✔
592
        }
593

594
        $reportFormat = self::getConfigData('report_format');
9✔
595
        if ($reportFormat !== null) {
9✔
596
            $this->reports = [$reportFormat => null];
×
597
        }
598

599
        $tabWidth = self::getConfigData('tab_width');
9✔
600
        if ($tabWidth !== null) {
9✔
601
            $this->tabWidth = (int) $tabWidth;
×
602
        }
603

604
        $encoding = self::getConfigData('encoding');
9✔
605
        if ($encoding !== null) {
9✔
606
            $this->encoding = strtolower($encoding);
×
607
        }
608

609
        $severity = self::getConfigData('severity');
9✔
610
        if ($severity !== null) {
9✔
611
            $this->errorSeverity   = (int) $severity;
×
612
            $this->warningSeverity = (int) $severity;
×
613
        }
614

615
        $severity = self::getConfigData('error_severity');
9✔
616
        if ($severity !== null) {
9✔
617
            $this->errorSeverity = (int) $severity;
×
618
        }
619

620
        $severity = self::getConfigData('warning_severity');
9✔
621
        if ($severity !== null) {
9✔
622
            $this->warningSeverity = (int) $severity;
×
623
        }
624

625
        $showWarnings = self::getConfigData('show_warnings');
9✔
626
        if ($showWarnings !== null) {
9✔
627
            $showWarnings = (bool) $showWarnings;
3✔
628
            if ($showWarnings === false) {
3✔
629
                $this->warningSeverity = 0;
3✔
630
            }
631
        }
632

633
        $reportWidth = self::getConfigData('report_width');
9✔
634
        if ($reportWidth !== null) {
9✔
635
            $this->reportWidth = $reportWidth;
3✔
636
        }
637

638
        $showProgress = self::getConfigData('show_progress');
9✔
639
        if ($showProgress !== null) {
9✔
640
            $this->showProgress = (bool) $showProgress;
×
641
        }
642

643
        $quiet = self::getConfigData('quiet');
9✔
644
        if ($quiet !== null) {
9✔
645
            $this->quiet = (bool) $quiet;
×
646
        }
647

648
        $colors = self::getConfigData('colors');
9✔
649
        if ($colors !== null) {
9✔
650
            $this->colors = (bool) $colors;
×
651
        }
652

653
        $cache = self::getConfigData('cache');
9✔
654
        if ($cache !== null) {
9✔
NEW
655
            $this->cache = (bool) $cache;
×
656
        }
657

658
        $parallel = self::getConfigData('parallel');
9✔
659
        if ($parallel !== null) {
9✔
NEW
660
            $this->parallel = max((int) $parallel, 1);
×
661
        }
662

663
    }//end restoreDefaults()
3✔
664

665

666
    /**
667
     * Processes a short (-e) command line argument.
668
     *
669
     * @param string $arg The command line argument.
670
     * @param int    $pos The position of the argument on the command line.
671
     *
672
     * @return void
673
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
674
     */
675
    public function processShortArgument($arg, $pos)
29✔
676
    {
677
        switch ($arg) {
9✔
678
        case 'h':
29✔
679
        case '?':
29✔
680
            $this->printUsage();
×
681
            throw new DeepExitException('', 0);
×
682
        case 'i' :
29✔
683
            $output = Standards::prepareInstalledStandardsForDisplay().PHP_EOL;
×
684
            throw new DeepExitException($output, 0);
×
685
        case 'v' :
29✔
686
            if ($this->quiet === true) {
×
687
                // Ignore when quiet mode is enabled.
688
                break;
×
689
            }
690

691
            $this->verbosity++;
×
692
            $this->overriddenDefaults['verbosity'] = true;
×
693
            break;
×
694
        case 'l' :
29✔
695
            $this->local = true;
×
696
            $this->overriddenDefaults['local'] = true;
×
697
            break;
×
698
        case 's' :
29✔
699
            $this->showSources = true;
×
700
            $this->overriddenDefaults['showSources'] = true;
×
701
            break;
×
702
        case 'a' :
29✔
703
            $this->interactive = true;
×
704
            $this->overriddenDefaults['interactive'] = true;
×
705
            break;
×
706
        case 'e':
29✔
707
            $this->explain = true;
×
708
            $this->overriddenDefaults['explain'] = true;
×
709
            break;
×
710
        case 'p' :
29✔
711
            if ($this->quiet === true) {
×
712
                // Ignore when quiet mode is enabled.
713
                break;
×
714
            }
715

716
            $this->showProgress = true;
×
717
            $this->overriddenDefaults['showProgress'] = true;
×
718
            break;
×
719
        case 'q' :
29✔
720
            // Quiet mode disables a few other settings as well.
721
            $this->quiet        = true;
×
722
            $this->showProgress = false;
×
723
            $this->verbosity    = 0;
×
724

725
            $this->overriddenDefaults['quiet'] = true;
×
726
            break;
×
727
        case 'm' :
29✔
728
            $this->recordErrors = false;
×
729
            $this->overriddenDefaults['recordErrors'] = true;
×
730
            break;
×
731
        case 'd' :
29✔
732
            $ini = explode('=', $this->cliArgs[($pos + 1)]);
29✔
733
            $this->cliArgs[($pos + 1)] = '';
29✔
734
            if (isset($ini[1]) === false) {
29✔
735
                // Set to true.
736
                $ini[1] = '1';
3✔
737
            }
738

739
            $current = ini_get($ini[0]);
29✔
740
            if ($current === false) {
29✔
741
                // Ini setting which doesn't exist, or is from an unavailable extension.
742
                // Silently ignore it.
743
                break;
4✔
744
            }
745

746
            $changed = ini_set($ini[0], $ini[1]);
25✔
747
            if ($changed === false && ini_get($ini[0]) !== $ini[1]) {
25✔
748
                $error  = sprintf('ERROR: Ini option "%s" cannot be changed at runtime.', $ini[0]).PHP_EOL;
12✔
749
                $error .= $this->printShortUsage(true);
12✔
750
                throw new DeepExitException($error, 3);
12✔
751
            }
752
            break;
13✔
753
        case 'n' :
×
754
            if (isset($this->overriddenDefaults['warningSeverity']) === false) {
×
755
                $this->warningSeverity = 0;
×
756
                $this->overriddenDefaults['warningSeverity'] = true;
×
757
            }
758
            break;
×
759
        case 'w' :
×
760
            if (isset($this->overriddenDefaults['warningSeverity']) === false) {
×
761
                $this->warningSeverity = $this->errorSeverity;
×
762
                $this->overriddenDefaults['warningSeverity'] = true;
×
763
            }
764
            break;
×
765
        default:
766
            if ($this->dieOnUnknownArg === false) {
×
767
                $unknown       = $this->unknown;
×
768
                $unknown[]     = $arg;
×
769
                $this->unknown = $unknown;
×
770
            } else {
771
                $this->processUnknownArgument('-'.$arg, $pos);
×
772
            }
773
        }//end switch
774

775
    }//end processShortArgument()
5✔
776

777

778
    /**
779
     * Processes a long (--example) command-line argument.
780
     *
781
     * @param string $arg The command line argument.
782
     * @param int    $pos The position of the argument on the command line.
783
     *
784
     * @return void
785
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
786
     */
787
    public function processLongArgument($arg, $pos)
183✔
788
    {
789
        switch ($arg) {
61✔
790
        case 'help':
183✔
791
            $this->printUsage();
×
792
            throw new DeepExitException('', 0);
×
793
        case 'version':
183✔
794
            $output  = 'PHP_CodeSniffer version '.self::VERSION.' ('.self::STABILITY.') ';
×
795
            $output .= 'by Squiz and PHPCSStandards'.PHP_EOL;
×
796
            throw new DeepExitException($output, 0);
×
797
        case 'colors':
183✔
798
            if (isset($this->overriddenDefaults['colors']) === true) {
×
799
                break;
×
800
            }
801

802
            $this->colors = true;
×
803
            $this->overriddenDefaults['colors'] = true;
×
804
            break;
×
805
        case 'no-colors':
183✔
806
            if (isset($this->overriddenDefaults['colors']) === true) {
×
807
                break;
×
808
            }
809

810
            $this->colors = false;
×
811
            $this->overriddenDefaults['colors'] = true;
×
812
            break;
×
813
        case 'cache':
183✔
814
            if (isset($this->overriddenDefaults['cache']) === true) {
×
815
                break;
×
816
            }
817

NEW
818
            $this->cache = true;
×
NEW
819
            $this->overriddenDefaults['cache'] = true;
×
UNCOV
820
            break;
×
821
        case 'no-cache':
183✔
822
            if (isset($this->overriddenDefaults['cache']) === true) {
×
823
                break;
×
824
            }
825

826
            $this->cache = false;
×
827
            $this->overriddenDefaults['cache'] = true;
×
828
            break;
×
829
        case 'ignore-annotations':
183✔
830
            if (isset($this->overriddenDefaults['annotations']) === true) {
×
831
                break;
×
832
            }
833

834
            $this->annotations = false;
×
835
            $this->overriddenDefaults['annotations'] = true;
×
836
            break;
×
837
        case 'config-set':
183✔
838
            if (isset($this->cliArgs[($pos + 1)]) === false
×
839
                || isset($this->cliArgs[($pos + 2)]) === false
×
840
            ) {
841
                $error  = 'ERROR: Setting a config option requires a name and value'.PHP_EOL.PHP_EOL;
×
842
                $error .= $this->printShortUsage(true);
×
843
                throw new DeepExitException($error, 3);
×
844
            }
845

846
            $key     = $this->cliArgs[($pos + 1)];
×
847
            $value   = $this->cliArgs[($pos + 2)];
×
848
            $current = self::getConfigData($key);
×
849

850
            try {
851
                $this->setConfigData($key, $value);
×
852
            } catch (Exception $e) {
×
853
                throw new DeepExitException($e->getMessage().PHP_EOL, 3);
×
854
            }
855

856
            $output = 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL;
×
857

858
            if ($current === null) {
×
859
                $output .= "Config value \"$key\" added successfully".PHP_EOL;
×
860
            } else {
861
                $output .= "Config value \"$key\" updated successfully; old value was \"$current\"".PHP_EOL;
×
862
            }
863
            throw new DeepExitException($output, 0);
×
864
        case 'config-delete':
183✔
865
            if (isset($this->cliArgs[($pos + 1)]) === false) {
×
866
                $error  = 'ERROR: Deleting a config option requires the name of the option'.PHP_EOL.PHP_EOL;
×
867
                $error .= $this->printShortUsage(true);
×
868
                throw new DeepExitException($error, 3);
×
869
            }
870

871
            $output = 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL;
×
872

873
            $key     = $this->cliArgs[($pos + 1)];
×
874
            $current = self::getConfigData($key);
×
875
            if ($current === null) {
×
876
                $output .= "Config value \"$key\" has not been set".PHP_EOL;
×
877
            } else {
878
                try {
879
                    $this->setConfigData($key, null);
×
880
                } catch (Exception $e) {
×
881
                    throw new DeepExitException($e->getMessage().PHP_EOL, 3);
×
882
                }
883

884
                $output .= "Config value \"$key\" removed successfully; old value was \"$current\"".PHP_EOL;
×
885
            }
886
            throw new DeepExitException($output, 0);
×
887
        case 'config-show':
183✔
888
            $data    = self::getAllConfigData();
×
889
            $output  = 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL;
×
890
            $output .= $this->prepareConfigDataForDisplay($data);
×
891
            throw new DeepExitException($output, 0);
×
892
        case 'runtime-set':
183✔
893
            if (isset($this->cliArgs[($pos + 1)]) === false
×
894
                || isset($this->cliArgs[($pos + 2)]) === false
×
895
            ) {
896
                $error  = 'ERROR: Setting a runtime config option requires a name and value'.PHP_EOL.PHP_EOL;
×
897
                $error .= $this->printShortUsage(true);
×
898
                throw new DeepExitException($error, 3);
×
899
            }
900

901
            $key   = $this->cliArgs[($pos + 1)];
×
902
            $value = $this->cliArgs[($pos + 2)];
×
903
            $this->cliArgs[($pos + 1)] = '';
×
904
            $this->cliArgs[($pos + 2)] = '';
×
905
            $this->setConfigData($key, $value, true);
×
906
            if (isset($this->overriddenDefaults['runtime-set']) === false) {
×
907
                $this->overriddenDefaults['runtime-set'] = [];
×
908
            }
909

910
            $this->overriddenDefaults['runtime-set'][$key] = true;
×
911
            break;
×
912
        default:
913
            if (substr($arg, 0, 7) === 'sniffs=') {
183✔
914
                if (isset($this->overriddenDefaults['sniffs']) === true) {
57✔
915
                    break;
3✔
916
                }
917

918
                $this->sniffs = $this->parseSniffCodes(substr($arg, 7), 'sniffs');
57✔
919
                $this->overriddenDefaults['sniffs'] = true;
21✔
920
            } else if (substr($arg, 0, 8) === 'exclude=') {
126✔
921
                if (isset($this->overriddenDefaults['exclude']) === true) {
57✔
922
                    break;
3✔
923
                }
924

925
                $this->exclude = $this->parseSniffCodes(substr($arg, 8), 'exclude');
57✔
926
                $this->overriddenDefaults['exclude'] = true;
21✔
927
            } else if (substr($arg, 0, 6) === 'cache=') {
69✔
UNCOV
928
                if ((isset($this->overriddenDefaults['cache']) === true
×
929
                    && $this->cache === false)
×
930
                    || isset($this->overriddenDefaults['cacheFile']) === true
×
931
                ) {
932
                    break;
×
933
                }
934

935
                // Turn caching on.
936
                $this->cache = true;
×
937
                $this->overriddenDefaults['cache'] = true;
×
938

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

941
                // It may not exist and return false instead.
942
                if ($this->cacheFile === false) {
×
943
                    $this->cacheFile = substr($arg, 6);
×
944

945
                    $dir = dirname($this->cacheFile);
×
946
                    if (is_dir($dir) === false) {
×
947
                        $error  = 'ERROR: The specified cache file path "'.$this->cacheFile.'" points to a non-existent directory'.PHP_EOL.PHP_EOL;
×
948
                        $error .= $this->printShortUsage(true);
×
949
                        throw new DeepExitException($error, 3);
×
950
                    }
951

952
                    if ($dir === '.') {
×
953
                        // Passed cache file is a file in the current directory.
954
                        $this->cacheFile = getcwd().'/'.basename($this->cacheFile);
×
955
                    } else {
956
                        if ($dir[0] === '/') {
×
957
                            // An absolute path.
958
                            $dir = Common::realpath($dir);
×
959
                        } else {
960
                            $dir = Common::realpath(getcwd().'/'.$dir);
×
961
                        }
962

963
                        if ($dir !== false) {
×
964
                            // Cache file path is relative.
965
                            $this->cacheFile = $dir.'/'.basename($this->cacheFile);
×
966
                        }
967
                    }
968
                }//end if
969

970
                $this->overriddenDefaults['cacheFile'] = true;
×
971

972
                if (is_dir($this->cacheFile) === true) {
×
973
                    $error  = 'ERROR: The specified cache file path "'.$this->cacheFile.'" is a directory'.PHP_EOL.PHP_EOL;
×
974
                    $error .= $this->printShortUsage(true);
×
975
                    throw new DeepExitException($error, 3);
×
976
                }
977
            } else if (substr($arg, 0, 10) === 'bootstrap=') {
69✔
978
                $files     = explode(',', substr($arg, 10));
×
979
                $bootstrap = [];
×
980
                foreach ($files as $file) {
×
981
                    $path = Common::realpath($file);
×
982
                    if ($path === false) {
×
983
                        $error  = 'ERROR: The specified bootstrap file "'.$file.'" does not exist'.PHP_EOL.PHP_EOL;
×
984
                        $error .= $this->printShortUsage(true);
×
985
                        throw new DeepExitException($error, 3);
×
986
                    }
987

988
                    $bootstrap[] = $path;
×
989
                }
990

991
                $this->bootstrap = array_merge($this->bootstrap, $bootstrap);
×
992
                $this->overriddenDefaults['bootstrap'] = true;
×
993
            } else if (substr($arg, 0, 10) === 'file-list=') {
69✔
994
                $fileList = substr($arg, 10);
×
995
                $path     = Common::realpath($fileList);
×
996
                if ($path === false) {
×
997
                    $error  = 'ERROR: The specified file list "'.$fileList.'" does not exist'.PHP_EOL.PHP_EOL;
×
998
                    $error .= $this->printShortUsage(true);
×
999
                    throw new DeepExitException($error, 3);
×
1000
                }
1001

1002
                $files = file($path);
×
1003
                foreach ($files as $inputFile) {
×
1004
                    $inputFile = trim($inputFile);
×
1005

1006
                    // Skip empty lines.
1007
                    if ($inputFile === '') {
×
1008
                        continue;
×
1009
                    }
1010

1011
                    $this->processFilePath($inputFile);
×
1012
                }
1013
            } else if (substr($arg, 0, 11) === 'stdin-path=') {
69✔
1014
                if (isset($this->overriddenDefaults['stdinPath']) === true) {
×
1015
                    break;
×
1016
                }
1017

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

1020
                // It may not exist and return false instead, so use whatever they gave us.
1021
                if ($this->stdinPath === false) {
×
1022
                    $this->stdinPath = trim(substr($arg, 11));
×
1023
                }
1024

1025
                $this->overriddenDefaults['stdinPath'] = true;
×
1026
            } else if (PHP_CODESNIFFER_CBF === false && substr($arg, 0, 12) === 'report-file=') {
69✔
1027
                if (isset($this->overriddenDefaults['reportFile']) === true) {
×
1028
                    break;
×
1029
                }
1030

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

1033
                // It may not exist and return false instead.
1034
                if ($this->reportFile === false) {
×
1035
                    $this->reportFile = substr($arg, 12);
×
1036

1037
                    $dir = Common::realpath(dirname($this->reportFile));
×
1038
                    if (is_dir($dir) === false) {
×
1039
                        $error  = 'ERROR: The specified report file path "'.$this->reportFile.'" points to a non-existent directory'.PHP_EOL.PHP_EOL;
×
1040
                        $error .= $this->printShortUsage(true);
×
1041
                        throw new DeepExitException($error, 3);
×
1042
                    }
1043

1044
                    $this->reportFile = $dir.'/'.basename($this->reportFile);
×
1045
                }//end if
1046

1047
                $this->overriddenDefaults['reportFile'] = true;
×
1048

1049
                if (is_dir($this->reportFile) === true) {
×
1050
                    $error  = 'ERROR: The specified report file path "'.$this->reportFile.'" is a directory'.PHP_EOL.PHP_EOL;
×
1051
                    $error .= $this->printShortUsage(true);
×
1052
                    throw new DeepExitException($error, 3);
×
1053
                }
1054
            } else if (substr($arg, 0, 13) === 'report-width=') {
69✔
1055
                if (isset($this->overriddenDefaults['reportWidth']) === true) {
9✔
1056
                    break;
3✔
1057
                }
1058

1059
                $this->reportWidth = substr($arg, 13);
9✔
1060
                $this->overriddenDefaults['reportWidth'] = true;
9✔
1061
            } else if (substr($arg, 0, 9) === 'basepath=') {
69✔
1062
                if (isset($this->overriddenDefaults['basepath']) === true) {
×
1063
                    break;
×
1064
                }
1065

1066
                $this->overriddenDefaults['basepath'] = true;
×
1067

1068
                if (substr($arg, 9) === '') {
×
1069
                    $this->basepath = null;
×
1070
                    break;
×
1071
                }
1072

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

1075
                // It may not exist and return false instead.
1076
                if ($this->basepath === false) {
×
1077
                    $this->basepath = substr($arg, 9);
×
1078
                }
1079

1080
                if (is_dir($this->basepath) === false) {
×
1081
                    $error  = 'ERROR: The specified basepath "'.$this->basepath.'" points to a non-existent directory'.PHP_EOL.PHP_EOL;
×
1082
                    $error .= $this->printShortUsage(true);
×
1083
                    throw new DeepExitException($error, 3);
×
1084
                }
1085
            } else if ((substr($arg, 0, 7) === 'report=' || substr($arg, 0, 7) === 'report-')) {
69✔
1086
                $reports = [];
×
1087

1088
                if ($arg[6] === '-') {
×
1089
                    // This is a report with file output.
1090
                    $split = strpos($arg, '=');
×
1091
                    if ($split === false) {
×
1092
                        $report = substr($arg, 7);
×
1093
                        $output = null;
×
1094
                    } else {
1095
                        $report = substr($arg, 7, ($split - 7));
×
1096
                        $output = substr($arg, ($split + 1));
×
1097
                        if ($output === false) {
×
1098
                            $output = null;
×
1099
                        } else {
1100
                            $dir = Common::realpath(dirname($output));
×
1101
                            if (is_dir($dir) === false) {
×
1102
                                $error  = 'ERROR: The specified '.$report.' report file path "'.$output.'" points to a non-existent directory'.PHP_EOL.PHP_EOL;
×
1103
                                $error .= $this->printShortUsage(true);
×
1104
                                throw new DeepExitException($error, 3);
×
1105
                            }
1106

1107
                            $output = $dir.'/'.basename($output);
×
1108

1109
                            if (is_dir($output) === true) {
×
1110
                                $error  = 'ERROR: The specified '.$report.' report file path "'.$output.'" is a directory'.PHP_EOL.PHP_EOL;
×
1111
                                $error .= $this->printShortUsage(true);
×
1112
                                throw new DeepExitException($error, 3);
×
1113
                            }
1114
                        }//end if
1115
                    }//end if
1116

1117
                    $reports[$report] = $output;
×
1118
                } else {
1119
                    // This is a single report.
1120
                    if (isset($this->overriddenDefaults['reports']) === true) {
×
1121
                        break;
×
1122
                    }
1123

1124
                    $reportNames = explode(',', substr($arg, 7));
×
1125
                    foreach ($reportNames as $report) {
×
1126
                        $reports[$report] = null;
×
1127
                    }
1128
                }//end if
1129

1130
                // Remove the default value so the CLI value overrides it.
1131
                if (isset($this->overriddenDefaults['reports']) === false) {
×
1132
                    $this->reports = $reports;
×
1133
                } else {
1134
                    $this->reports = array_merge($this->reports, $reports);
×
1135
                }
1136

1137
                $this->overriddenDefaults['reports'] = true;
×
1138
            } else if (substr($arg, 0, 7) === 'filter=') {
69✔
1139
                if (isset($this->overriddenDefaults['filter']) === true) {
×
1140
                    break;
×
1141
                }
1142

1143
                $this->filter = substr($arg, 7);
×
1144
                $this->overriddenDefaults['filter'] = true;
×
1145
            } else if (substr($arg, 0, 9) === 'standard=') {
69✔
1146
                $standards = trim(substr($arg, 9));
9✔
1147
                if ($standards !== '') {
9✔
1148
                    $this->standards = explode(',', $standards);
9✔
1149
                }
1150

1151
                $this->overriddenDefaults['standards'] = true;
9✔
1152
            } else if (substr($arg, 0, 11) === 'extensions=') {
60✔
1153
                if (isset($this->overriddenDefaults['extensions']) === true) {
30✔
1154
                    break;
3✔
1155
                }
1156

1157
                $extensionsString = substr($arg, 11);
30✔
1158
                $newExtensions    = [];
30✔
1159
                if (empty($extensionsString) === false) {
30✔
1160
                    $extensions = explode(',', $extensionsString);
27✔
1161
                    foreach ($extensions as $ext) {
27✔
1162
                        if (strpos($ext, '/') !== false) {
27✔
1163
                            // They specified the tokenizer too.
1164
                            list($ext, $tokenizer) = explode('/', $ext);
12✔
1165
                            if (strtoupper($tokenizer) !== 'PHP') {
12✔
1166
                                $error  = 'ERROR: Specifying the tokenizer to use for an extension is no longer supported.'.PHP_EOL;
9✔
1167
                                $error .= 'PHP_CodeSniffer >= 4.0 only supports scanning PHP files.'.PHP_EOL;
9✔
1168
                                $error .= 'Received: '.substr($arg, 11).PHP_EOL.PHP_EOL;
9✔
1169
                                $error .= $this->printShortUsage(true);
9✔
1170
                                throw new DeepExitException($error, 3);
9✔
1171
                            }
1172
                        }
1173

1174
                        $newExtensions[$ext] = 'PHP';
21✔
1175
                    }
1176
                }
1177

1178
                $this->extensions = $newExtensions;
21✔
1179
                $this->overriddenDefaults['extensions'] = true;
21✔
1180
            } else if (substr($arg, 0, 7) === 'suffix=') {
30✔
1181
                if (isset($this->overriddenDefaults['suffix']) === true) {
×
1182
                    break;
×
1183
                }
1184

1185
                $this->suffix = substr($arg, 7);
×
1186
                $this->overriddenDefaults['suffix'] = true;
×
1187
            } else if (substr($arg, 0, 9) === 'parallel=') {
30✔
1188
                if (isset($this->overriddenDefaults['parallel']) === true) {
×
1189
                    break;
×
1190
                }
1191

1192
                $this->parallel = max((int) substr($arg, 9), 1);
×
1193
                $this->overriddenDefaults['parallel'] = true;
×
1194
            } else if (substr($arg, 0, 9) === 'severity=') {
30✔
1195
                $this->errorSeverity   = (int) substr($arg, 9);
×
1196
                $this->warningSeverity = $this->errorSeverity;
×
1197
                if (isset($this->overriddenDefaults['errorSeverity']) === false) {
×
1198
                    $this->overriddenDefaults['errorSeverity'] = true;
×
1199
                }
1200

1201
                if (isset($this->overriddenDefaults['warningSeverity']) === false) {
×
1202
                    $this->overriddenDefaults['warningSeverity'] = true;
×
1203
                }
1204
            } else if (substr($arg, 0, 15) === 'error-severity=') {
30✔
1205
                if (isset($this->overriddenDefaults['errorSeverity']) === true) {
×
1206
                    break;
×
1207
                }
1208

1209
                $this->errorSeverity = (int) substr($arg, 15);
×
1210
                $this->overriddenDefaults['errorSeverity'] = true;
×
1211
            } else if (substr($arg, 0, 17) === 'warning-severity=') {
30✔
1212
                if (isset($this->overriddenDefaults['warningSeverity']) === true) {
×
1213
                    break;
×
1214
                }
1215

1216
                $this->warningSeverity = (int) substr($arg, 17);
×
1217
                $this->overriddenDefaults['warningSeverity'] = true;
×
1218
            } else if (substr($arg, 0, 7) === 'ignore=') {
30✔
1219
                if (isset($this->overriddenDefaults['ignored']) === true) {
×
1220
                    break;
×
1221
                }
1222

1223
                // Split the ignore string on commas, unless the comma is escaped
1224
                // using 1 or 3 slashes (\, or \\\,).
1225
                $patterns = preg_split(
×
1226
                    '/(?<=(?<!\\\\)\\\\\\\\),|(?<!\\\\),/',
×
1227
                    substr($arg, 7)
×
1228
                );
1229

1230
                $ignored = [];
×
1231
                foreach ($patterns as $pattern) {
×
1232
                    $pattern = trim($pattern);
×
1233
                    if ($pattern === '') {
×
1234
                        continue;
×
1235
                    }
1236

1237
                    $ignored[$pattern] = 'absolute';
×
1238
                }
1239

1240
                $this->ignored = $ignored;
×
1241
                $this->overriddenDefaults['ignored'] = true;
×
1242
            } else if (substr($arg, 0, 10) === 'generator='
30✔
1243
                && PHP_CODESNIFFER_CBF === false
30✔
1244
            ) {
1245
                if (isset($this->overriddenDefaults['generator']) === true) {
30✔
1246
                    break;
3✔
1247
                }
1248

1249
                $generatorName          = substr($arg, 10);
30✔
1250
                $lowerCaseGeneratorName = strtolower($generatorName);
30✔
1251

1252
                if (isset($this->validGenerators[$lowerCaseGeneratorName]) === false) {
30✔
1253
                    $validOptions = implode(', ', $this->validGenerators);
9✔
1254
                    $validOptions = substr_replace($validOptions, ' and', strrpos($validOptions, ','), 1);
9✔
1255
                    $error        = sprintf(
9✔
1256
                        'ERROR: "%s" is not a valid generator. The following generators are supported: %s.'.PHP_EOL.PHP_EOL,
9✔
1257
                        $generatorName,
9✔
1258
                        $validOptions
9✔
1259
                    );
6✔
1260
                    $error       .= $this->printShortUsage(true);
9✔
1261
                    throw new DeepExitException($error, 3);
9✔
1262
                }
1263

1264
                $this->generator = $this->validGenerators[$lowerCaseGeneratorName];
21✔
1265
                $this->overriddenDefaults['generator'] = true;
21✔
1266
            } else if (substr($arg, 0, 9) === 'encoding=') {
×
1267
                if (isset($this->overriddenDefaults['encoding']) === true) {
×
1268
                    break;
×
1269
                }
1270

1271
                $this->encoding = strtolower(substr($arg, 9));
×
1272
                $this->overriddenDefaults['encoding'] = true;
×
1273
            } else if (substr($arg, 0, 10) === 'tab-width=') {
×
1274
                if (isset($this->overriddenDefaults['tabWidth']) === true) {
×
1275
                    break;
×
1276
                }
1277

1278
                $this->tabWidth = (int) substr($arg, 10);
×
1279
                $this->overriddenDefaults['tabWidth'] = true;
×
1280
            } else {
1281
                if ($this->dieOnUnknownArg === false) {
×
1282
                    $eqPos = strpos($arg, '=');
×
1283
                    try {
1284
                        $unknown = $this->unknown;
×
1285

1286
                        if ($eqPos === false) {
×
1287
                            $unknown[$arg] = $arg;
×
1288
                        } else {
1289
                            $value         = substr($arg, ($eqPos + 1));
×
1290
                            $arg           = substr($arg, 0, $eqPos);
×
1291
                            $unknown[$arg] = $value;
×
1292
                        }
1293

1294
                        $this->unknown = $unknown;
×
1295
                    } catch (RuntimeException $e) {
×
1296
                        // Value is not valid, so just ignore it.
1297
                    }
1298
                } else {
1299
                    $this->processUnknownArgument('--'.$arg, $pos);
×
1300
                }
1301
            }//end if
1302
            break;
93✔
1303
        }//end switch
1304

1305
    }//end processLongArgument()
31✔
1306

1307

1308
    /**
1309
     * Parse supplied string into a list of validated sniff codes.
1310
     *
1311
     * @param string $input    Comma-separated string of sniff codes.
1312
     * @param string $argument The name of the argument which is being processed.
1313
     *
1314
     * @return array<string>
1315
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException When any of the provided codes are not valid as sniff codes.
1316
     */
1317
    private function parseSniffCodes($input, $argument)
114✔
1318
    {
1319
        $errors = [];
114✔
1320
        $sniffs = [];
114✔
1321

1322
        $possibleSniffs = array_filter(explode(',', $input));
114✔
1323

1324
        if ($possibleSniffs === []) {
114✔
1325
            $errors[] = 'No codes specified / empty argument';
18✔
1326
        }
1327

1328
        foreach ($possibleSniffs as $sniff) {
114✔
1329
            $sniff = trim($sniff);
96✔
1330

1331
            $partCount = substr_count($sniff, '.');
96✔
1332
            if ($partCount === 2) {
96✔
1333
                // Correct number of parts.
1334
                $sniffs[] = $sniff;
54✔
1335
                continue;
54✔
1336
            }
1337

1338
            if ($partCount === 0) {
54✔
1339
                $errors[] = 'Standard codes are not supported: '.$sniff;
12✔
1340
            } else if ($partCount === 1) {
42✔
1341
                $errors[] = 'Category codes are not supported: '.$sniff;
18✔
1342
            } else if ($partCount === 3) {
24✔
1343
                $errors[] = 'Message codes are not supported: '.$sniff;
18✔
1344
            } else {
1345
                $errors[] = 'Too many parts: '.$sniff;
12✔
1346
            }
1347

1348
            if ($partCount > 2) {
54✔
1349
                $parts    = explode('.', $sniff, 4);
24✔
1350
                $sniffs[] = $parts[0].'.'.$parts[1].'.'.$parts[2];
24✔
1351
            }
1352
        }//end foreach
1353

1354
        $sniffs = array_reduce(
114✔
1355
            $sniffs,
114✔
1356
            static function ($carry, $item) {
76✔
1357
                $lower = strtolower($item);
78✔
1358

1359
                foreach ($carry as $found) {
78✔
1360
                    if ($lower === strtolower($found)) {
36✔
1361
                        // This sniff is already in our list.
1362
                        return $carry;
24✔
1363
                    }
1364
                }
1365

1366
                $carry[] = $item;
78✔
1367

1368
                return $carry;
78✔
1369
            },
114✔
1370
            []
114✔
1371
        );
76✔
1372

1373
        if ($errors !== []) {
114✔
1374
            $error  = 'ERROR: The --'.$argument.' option only supports sniff codes.'.PHP_EOL;
72✔
1375
            $error .= 'Sniff codes are in the form "Standard.Category.Sniff".'.PHP_EOL;
72✔
1376
            $error .= PHP_EOL;
72✔
1377
            $error .= 'The following problems were detected:'.PHP_EOL;
72✔
1378
            $error .= '* '.implode(PHP_EOL.'* ', $errors).PHP_EOL;
72✔
1379

1380
            if ($sniffs !== []) {
72✔
1381
                $error .= PHP_EOL;
36✔
1382
                $error .= 'Perhaps try --'.$argument.'="'.implode(',', $sniffs).'" instead.'.PHP_EOL;
36✔
1383
            }
1384

1385
            $error .= PHP_EOL;
72✔
1386
            $error .= $this->printShortUsage(true);
72✔
1387
            throw new DeepExitException(ltrim($error), 3);
72✔
1388
        }
1389

1390
        return $sniffs;
42✔
1391

1392
    }//end parseSniffCodes()
1393

1394

1395
    /**
1396
     * Processes an unknown command line argument.
1397
     *
1398
     * Assumes all unknown arguments are files and folders to check.
1399
     *
1400
     * @param string $arg The command line argument.
1401
     * @param int    $pos The position of the argument on the command line.
1402
     *
1403
     * @return void
1404
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
1405
     */
1406
    public function processUnknownArgument($arg, $pos)
×
1407
    {
1408
        // We don't know about any additional switches; just files.
1409
        if ($arg[0] === '-') {
×
1410
            if ($this->dieOnUnknownArg === false) {
×
1411
                return;
×
1412
            }
1413

1414
            $error  = "ERROR: option \"$arg\" not known".PHP_EOL.PHP_EOL;
×
1415
            $error .= $this->printShortUsage(true);
×
1416
            throw new DeepExitException($error, 3);
×
1417
        }
1418

1419
        $this->processFilePath($arg);
×
1420

1421
    }//end processUnknownArgument()
1422

1423

1424
    /**
1425
     * Processes a file path and add it to the file list.
1426
     *
1427
     * @param string $path The path to the file to add.
1428
     *
1429
     * @return void
1430
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
1431
     */
1432
    public function processFilePath($path)
×
1433
    {
1434
        // If we are processing STDIN, don't record any files to check.
1435
        if ($this->stdin === true) {
×
1436
            return;
×
1437
        }
1438

1439
        $file = Common::realpath($path);
×
1440
        if (file_exists($file) === false) {
×
1441
            if ($this->dieOnUnknownArg === false) {
×
1442
                return;
×
1443
            }
1444

1445
            $error  = 'ERROR: The file "'.$path.'" does not exist.'.PHP_EOL.PHP_EOL;
×
1446
            $error .= $this->printShortUsage(true);
×
1447
            throw new DeepExitException($error, 3);
×
1448
        } else {
1449
            // Can't modify the files array directly because it's not a real
1450
            // class member, so need to use this little get/modify/set trick.
1451
            $files       = $this->files;
×
1452
            $files[]     = $file;
×
1453
            $this->files = $files;
×
1454
            $this->overriddenDefaults['files'] = true;
×
1455
        }
1456

1457
    }//end processFilePath()
1458

1459

1460
    /**
1461
     * Prints out the usage information for this script.
1462
     *
1463
     * @return void
1464
     */
1465
    public function printUsage()
×
1466
    {
1467
        echo PHP_EOL;
×
1468

1469
        if (PHP_CODESNIFFER_CBF === true) {
×
1470
            $this->printPHPCBFUsage();
×
1471
        } else {
1472
            $this->printPHPCSUsage();
×
1473
        }
1474

1475
        echo PHP_EOL;
×
1476

1477
    }//end printUsage()
1478

1479

1480
    /**
1481
     * Prints out the short usage information for this script.
1482
     *
1483
     * @param bool $return If TRUE, the usage string is returned
1484
     *                     instead of output to screen.
1485
     *
1486
     * @return string|void
1487
     */
1488
    public function printShortUsage($return=false)
×
1489
    {
1490
        if (PHP_CODESNIFFER_CBF === true) {
×
1491
            $usage = 'Run "phpcbf --help" for usage information';
×
1492
        } else {
1493
            $usage = 'Run "phpcs --help" for usage information';
×
1494
        }
1495

1496
        $usage .= PHP_EOL.PHP_EOL;
×
1497

1498
        if ($return === true) {
×
1499
            return $usage;
×
1500
        }
1501

1502
        echo $usage;
×
1503

1504
    }//end printShortUsage()
1505

1506

1507
    /**
1508
     * Prints out the usage information for PHPCS.
1509
     *
1510
     * @return void
1511
     */
1512
    public function printPHPCSUsage()
×
1513
    {
1514
        $longOptions   = explode(',', Help::DEFAULT_LONG_OPTIONS);
×
1515
        $longOptions[] = 'cache';
×
1516
        $longOptions[] = 'no-cache';
×
1517
        $longOptions[] = 'report';
×
1518
        $longOptions[] = 'report-file';
×
1519
        $longOptions[] = 'report-report';
×
1520
        $longOptions[] = 'config-explain';
×
1521
        $longOptions[] = 'config-set';
×
1522
        $longOptions[] = 'config-delete';
×
1523
        $longOptions[] = 'config-show';
×
1524
        $longOptions[] = 'generator';
×
1525

1526
        $shortOptions = Help::DEFAULT_SHORT_OPTIONS.'aems';
×
1527

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

1530
    }//end printPHPCSUsage()
1531

1532

1533
    /**
1534
     * Prints out the usage information for PHPCBF.
1535
     *
1536
     * @return void
1537
     */
1538
    public function printPHPCBFUsage()
×
1539
    {
1540
        $longOptions   = explode(',', Help::DEFAULT_LONG_OPTIONS);
×
1541
        $longOptions[] = 'suffix';
×
1542
        $shortOptions  = Help::DEFAULT_SHORT_OPTIONS;
×
1543

1544
        (new Help($this, $longOptions, $shortOptions))->display();
×
1545

1546
    }//end printPHPCBFUsage()
1547

1548

1549
    /**
1550
     * Get a single config value.
1551
     *
1552
     * @param string $key The name of the config value.
1553
     *
1554
     * @return string|null
1555
     * @see    setConfigData()
1556
     * @see    getAllConfigData()
1557
     */
1558
    public static function getConfigData($key)
6✔
1559
    {
1560
        $phpCodeSnifferConfig = self::getAllConfigData();
6✔
1561

1562
        if ($phpCodeSnifferConfig === null) {
6✔
1563
            return null;
×
1564
        }
1565

1566
        if (isset($phpCodeSnifferConfig[$key]) === false) {
6✔
1567
            return null;
6✔
1568
        }
1569

1570
        return $phpCodeSnifferConfig[$key];
6✔
1571

1572
    }//end getConfigData()
1573

1574

1575
    /**
1576
     * Get the path to an executable utility.
1577
     *
1578
     * @param string $name The name of the executable utility.
1579
     *
1580
     * @return string|null
1581
     * @see    getConfigData()
1582
     */
1583
    public static function getExecutablePath($name)
×
1584
    {
1585
        $data = self::getConfigData($name.'_path');
×
1586
        if ($data !== null) {
×
1587
            return $data;
×
1588
        }
1589

1590
        if ($name === "php") {
×
1591
            // For php, we know the executable path. There's no need to look it up.
1592
            return PHP_BINARY;
×
1593
        }
1594

1595
        if (array_key_exists($name, self::$executablePaths) === true) {
×
1596
            return self::$executablePaths[$name];
×
1597
        }
1598

1599
        if (PHP_OS_FAMILY === 'Windows') {
×
1600
            $cmd = 'where '.escapeshellarg($name).' 2> nul';
×
1601
        } else {
1602
            $cmd = 'which '.escapeshellarg($name).' 2> /dev/null';
×
1603
        }
1604

1605
        $result = exec($cmd, $output, $retVal);
×
1606
        if ($retVal !== 0) {
×
1607
            $result = null;
×
1608
        }
1609

1610
        self::$executablePaths[$name] = $result;
×
1611
        return $result;
×
1612

1613
    }//end getExecutablePath()
1614

1615

1616
    /**
1617
     * Set a single config value.
1618
     *
1619
     * @param string      $key   The name of the config value.
1620
     * @param string|null $value The value to set. If null, the config
1621
     *                           entry is deleted, reverting it to the
1622
     *                           default value.
1623
     * @param boolean     $temp  Set this config data temporarily for this
1624
     *                           script run. This will not write the config
1625
     *                           data to the config file.
1626
     *
1627
     * @return bool
1628
     * @see    getConfigData()
1629
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the config file can not be written.
1630
     */
1631
    public function setConfigData($key, $value, $temp=false)
×
1632
    {
1633
        if (isset($this->overriddenDefaults['runtime-set']) === true
×
1634
            && isset($this->overriddenDefaults['runtime-set'][$key]) === true
×
1635
        ) {
1636
            return false;
×
1637
        }
1638

1639
        if ($temp === false) {
×
1640
            $path = '';
×
1641
            if (is_callable('\Phar::running') === true) {
×
1642
                $path = Phar::running(false);
×
1643
            }
1644

1645
            if ($path !== '') {
×
1646
                $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1647
            } else {
1648
                $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1649
            }
1650

1651
            if (is_file($configFile) === true
×
1652
                && is_writable($configFile) === false
×
1653
            ) {
1654
                $error = 'ERROR: Config file '.$configFile.' is not writable'.PHP_EOL.PHP_EOL;
×
1655
                throw new DeepExitException($error, 3);
×
1656
            }
1657
        }//end if
1658

1659
        $phpCodeSnifferConfig = self::getAllConfigData();
×
1660

1661
        if ($value === null) {
×
1662
            if (isset($phpCodeSnifferConfig[$key]) === true) {
×
1663
                unset($phpCodeSnifferConfig[$key]);
×
1664
            }
1665
        } else {
1666
            $phpCodeSnifferConfig[$key] = $value;
×
1667
        }
1668

1669
        if ($temp === false) {
×
1670
            $output  = '<'.'?php'."\n".' $phpCodeSnifferConfig = ';
×
1671
            $output .= var_export($phpCodeSnifferConfig, true);
×
1672
            $output .= ";\n?".'>';
×
1673

1674
            if (file_put_contents($configFile, $output) === false) {
×
1675
                $error = 'ERROR: Config file '.$configFile.' could not be written'.PHP_EOL.PHP_EOL;
×
1676
                throw new DeepExitException($error, 3);
×
1677
            }
1678

1679
            self::$configDataFile = $configFile;
×
1680
        }
1681

1682
        self::$configData = $phpCodeSnifferConfig;
×
1683

1684
        // If the installed paths are being set, make sure all known
1685
        // standards paths are added to the autoloader.
1686
        if ($key === 'installed_paths') {
×
1687
            $installedStandards = Standards::getInstalledStandardDetails();
×
1688
            foreach ($installedStandards as $details) {
×
1689
                Autoload::addSearchPath($details['path'], $details['namespace']);
×
1690
            }
1691
        }
1692

1693
        return true;
×
1694

1695
    }//end setConfigData()
1696

1697

1698
    /**
1699
     * Get all config data.
1700
     *
1701
     * @return array<string, string>
1702
     * @see    getConfigData()
1703
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the config file could not be read.
1704
     */
1705
    public static function getAllConfigData()
×
1706
    {
1707
        if (self::$configData !== null) {
×
1708
            return self::$configData;
×
1709
        }
1710

1711
        $path = '';
×
1712
        if (is_callable('\Phar::running') === true) {
×
1713
            $path = Phar::running(false);
×
1714
        }
1715

1716
        if ($path !== '') {
×
1717
            $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1718
        } else {
1719
            $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1720
            if (is_file($configFile) === false
×
1721
                && strpos('@data_dir@', '@data_dir') === false
×
1722
            ) {
1723
                $configFile = '@data_dir@/PHP_CodeSniffer/CodeSniffer.conf';
×
1724
            }
1725
        }
1726

1727
        if (is_file($configFile) === false) {
×
1728
            self::$configData = [];
×
1729
            return [];
×
1730
        }
1731

1732
        if (Common::isReadable($configFile) === false) {
×
1733
            $error = 'ERROR: Config file '.$configFile.' is not readable'.PHP_EOL.PHP_EOL;
×
1734
            throw new DeepExitException($error, 3);
×
1735
        }
1736

1737
        include $configFile;
×
1738
        self::$configDataFile = $configFile;
×
1739
        self::$configData     = $phpCodeSnifferConfig;
×
1740
        return self::$configData;
×
1741

1742
    }//end getAllConfigData()
1743

1744

1745
    /**
1746
     * Prepares the gathered config data for display.
1747
     *
1748
     * @param array<string, string> $data The config data to format for display.
1749
     *
1750
     * @return string
1751
     */
1752
    public function prepareConfigDataForDisplay($data)
18✔
1753
    {
1754
        if (empty($data) === true) {
18✔
1755
            return '';
6✔
1756
        }
1757

1758
        $max  = 0;
12✔
1759
        $keys = array_keys($data);
12✔
1760
        foreach ($keys as $key) {
12✔
1761
            $len = strlen($key);
12✔
1762
            if ($len > $max) {
12✔
1763
                $max = $len;
12✔
1764
            }
1765
        }
1766

1767
        $max += 2;
12✔
1768
        ksort($data);
12✔
1769

1770
        $output = '';
12✔
1771
        foreach ($data as $name => $value) {
12✔
1772
            $output .= str_pad($name.': ', $max).$value.PHP_EOL;
12✔
1773
        }
1774

1775
        return $output;
12✔
1776

1777
    }//end prepareConfigDataForDisplay()
1778

1779

1780
    /**
1781
     * Prints out the gathered config data.
1782
     *
1783
     * @param array<string, string> $data The config data to print.
1784
     *
1785
     * @deprecated 4.0.0 Use `echo Config::prepareConfigDataForDisplay()` instead.
1786
     *
1787
     * @return void
1788
     */
1789
    public function printConfigData($data)
3✔
1790
    {
1791
        echo $this->prepareConfigDataForDisplay($data);
3✔
1792

1793
    }//end printConfigData()
1✔
1794

1795

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