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

PHPCSStandards / PHP_CodeSniffer / 14732455750

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

Pull #1054

github

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

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

1 existing line in 1 file now uncovered.

19548 of 24965 relevant lines covered (78.3%)

86.08 hits per line

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

34.1
/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
        if (defined('PHP_CODESNIFFER_IN_TESTS') === false) {
9✔
654
            $cache = self::getConfigData('cache');
×
655
            if ($cache !== null) {
×
656
                $this->cache = (bool) $cache;
×
657
            }
658

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

665
    }//end restoreDefaults()
3✔
666

667

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

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

721
            $this->showProgress = true;
×
722
            $this->overriddenDefaults['showProgress'] = true;
×
723
            break;
×
724
        case 'q' :
29✔
725
            // Quiet mode disables a few other settings as well.
726
            $this->quiet        = true;
×
727
            $this->showProgress = false;
×
728
            $this->verbosity    = 0;
×
729

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

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

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

780
    }//end processShortArgument()
5✔
781

782

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

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

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

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

836
            $this->cache = false;
×
837
            $this->overriddenDefaults['cache'] = true;
×
838
            break;
×
839
        case 'ignore-annotations':
183✔
840
            if (isset($this->overriddenDefaults['annotations']) === true) {
×
841
                break;
×
842
            }
843

844
            $this->annotations = false;
×
845
            $this->overriddenDefaults['annotations'] = true;
×
846
            break;
×
847
        case 'config-set':
183✔
848
            if (isset($this->cliArgs[($pos + 1)]) === false
×
849
                || isset($this->cliArgs[($pos + 2)]) === false
×
850
            ) {
851
                $error  = 'ERROR: Setting a config option requires a name and value'.PHP_EOL.PHP_EOL;
×
852
                $error .= $this->printShortUsage(true);
×
853
                throw new DeepExitException($error, 3);
×
854
            }
855

856
            $key     = $this->cliArgs[($pos + 1)];
×
857
            $value   = $this->cliArgs[($pos + 2)];
×
858
            $current = self::getConfigData($key);
×
859

860
            try {
861
                $this->setConfigData($key, $value);
×
862
            } catch (Exception $e) {
×
863
                throw new DeepExitException($e->getMessage().PHP_EOL, 3);
×
864
            }
865

866
            $output = 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL;
×
867

868
            if ($current === null) {
×
869
                $output .= "Config value \"$key\" added successfully".PHP_EOL;
×
870
            } else {
871
                $output .= "Config value \"$key\" updated successfully; old value was \"$current\"".PHP_EOL;
×
872
            }
873
            throw new DeepExitException($output, 0);
×
874
        case 'config-delete':
183✔
875
            if (isset($this->cliArgs[($pos + 1)]) === false) {
×
876
                $error  = 'ERROR: Deleting a config option requires the name of the option'.PHP_EOL.PHP_EOL;
×
877
                $error .= $this->printShortUsage(true);
×
878
                throw new DeepExitException($error, 3);
×
879
            }
880

881
            $output = 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL;
×
882

883
            $key     = $this->cliArgs[($pos + 1)];
×
884
            $current = self::getConfigData($key);
×
885
            if ($current === null) {
×
886
                $output .= "Config value \"$key\" has not been set".PHP_EOL;
×
887
            } else {
888
                try {
889
                    $this->setConfigData($key, null);
×
890
                } catch (Exception $e) {
×
891
                    throw new DeepExitException($e->getMessage().PHP_EOL, 3);
×
892
                }
893

894
                $output .= "Config value \"$key\" removed successfully; old value was \"$current\"".PHP_EOL;
×
895
            }
896
            throw new DeepExitException($output, 0);
×
897
        case 'config-show':
183✔
898
            ob_start();
×
899
            $data = self::getAllConfigData();
×
900
            echo 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL;
×
901
            $this->printConfigData($data);
×
902
            $output = ob_get_contents();
×
903
            ob_end_clean();
×
904
            throw new DeepExitException($output, 0);
×
905
        case 'runtime-set':
183✔
906
            if (isset($this->cliArgs[($pos + 1)]) === false
×
907
                || isset($this->cliArgs[($pos + 2)]) === false
×
908
            ) {
909
                $error  = 'ERROR: Setting a runtime config option requires a name and value'.PHP_EOL.PHP_EOL;
×
910
                $error .= $this->printShortUsage(true);
×
911
                throw new DeepExitException($error, 3);
×
912
            }
913

914
            $key   = $this->cliArgs[($pos + 1)];
×
915
            $value = $this->cliArgs[($pos + 2)];
×
916
            $this->cliArgs[($pos + 1)] = '';
×
917
            $this->cliArgs[($pos + 2)] = '';
×
918
            $this->setConfigData($key, $value, true);
×
919
            if (isset($this->overriddenDefaults['runtime-set']) === false) {
×
920
                $this->overriddenDefaults['runtime-set'] = [];
×
921
            }
922

923
            $this->overriddenDefaults['runtime-set'][$key] = true;
×
924
            break;
×
925
        default:
926
            if (substr($arg, 0, 7) === 'sniffs=') {
183✔
927
                if (isset($this->overriddenDefaults['sniffs']) === true) {
57✔
928
                    break;
3✔
929
                }
930

931
                $this->sniffs = $this->parseSniffCodes(substr($arg, 7), 'sniffs');
57✔
932
                $this->overriddenDefaults['sniffs'] = true;
21✔
933
            } else if (substr($arg, 0, 8) === 'exclude=') {
126✔
934
                if (isset($this->overriddenDefaults['exclude']) === true) {
57✔
935
                    break;
3✔
936
                }
937

938
                $this->exclude = $this->parseSniffCodes(substr($arg, 8), 'exclude');
57✔
939
                $this->overriddenDefaults['exclude'] = true;
21✔
940
            } else if (defined('PHP_CODESNIFFER_IN_TESTS') === false
69✔
941
                && substr($arg, 0, 6) === 'cache='
69✔
942
            ) {
943
                if ((isset($this->overriddenDefaults['cache']) === true
×
944
                    && $this->cache === false)
×
945
                    || isset($this->overriddenDefaults['cacheFile']) === true
×
946
                ) {
947
                    break;
×
948
                }
949

950
                // Turn caching on.
951
                $this->cache = true;
×
952
                $this->overriddenDefaults['cache'] = true;
×
953

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

956
                // It may not exist and return false instead.
957
                if ($this->cacheFile === false) {
×
958
                    $this->cacheFile = substr($arg, 6);
×
959

960
                    $dir = dirname($this->cacheFile);
×
961
                    if (is_dir($dir) === false) {
×
962
                        $error  = 'ERROR: The specified cache file path "'.$this->cacheFile.'" points to a non-existent directory'.PHP_EOL.PHP_EOL;
×
963
                        $error .= $this->printShortUsage(true);
×
964
                        throw new DeepExitException($error, 3);
×
965
                    }
966

967
                    if ($dir === '.') {
×
968
                        // Passed cache file is a file in the current directory.
969
                        $this->cacheFile = getcwd().'/'.basename($this->cacheFile);
×
970
                    } else {
971
                        if ($dir[0] === '/') {
×
972
                            // An absolute path.
973
                            $dir = Common::realpath($dir);
×
974
                        } else {
975
                            $dir = Common::realpath(getcwd().'/'.$dir);
×
976
                        }
977

978
                        if ($dir !== false) {
×
979
                            // Cache file path is relative.
980
                            $this->cacheFile = $dir.'/'.basename($this->cacheFile);
×
981
                        }
982
                    }
983
                }//end if
984

985
                $this->overriddenDefaults['cacheFile'] = true;
×
986

987
                if (is_dir($this->cacheFile) === true) {
×
988
                    $error  = 'ERROR: The specified cache file path "'.$this->cacheFile.'" is a directory'.PHP_EOL.PHP_EOL;
×
989
                    $error .= $this->printShortUsage(true);
×
990
                    throw new DeepExitException($error, 3);
×
991
                }
992
            } else if (substr($arg, 0, 10) === 'bootstrap=') {
69✔
993
                $files     = explode(',', substr($arg, 10));
×
994
                $bootstrap = [];
×
995
                foreach ($files as $file) {
×
996
                    $path = Common::realpath($file);
×
997
                    if ($path === false) {
×
998
                        $error  = 'ERROR: The specified bootstrap file "'.$file.'" does not exist'.PHP_EOL.PHP_EOL;
×
999
                        $error .= $this->printShortUsage(true);
×
1000
                        throw new DeepExitException($error, 3);
×
1001
                    }
1002

1003
                    $bootstrap[] = $path;
×
1004
                }
1005

1006
                $this->bootstrap = array_merge($this->bootstrap, $bootstrap);
×
1007
                $this->overriddenDefaults['bootstrap'] = true;
×
1008
            } else if (substr($arg, 0, 10) === 'file-list=') {
69✔
1009
                $fileList = substr($arg, 10);
×
1010
                $path     = Common::realpath($fileList);
×
1011
                if ($path === false) {
×
1012
                    $error  = 'ERROR: The specified file list "'.$fileList.'" does not exist'.PHP_EOL.PHP_EOL;
×
1013
                    $error .= $this->printShortUsage(true);
×
1014
                    throw new DeepExitException($error, 3);
×
1015
                }
1016

1017
                $files = file($path);
×
1018
                foreach ($files as $inputFile) {
×
1019
                    $inputFile = trim($inputFile);
×
1020

1021
                    // Skip empty lines.
1022
                    if ($inputFile === '') {
×
1023
                        continue;
×
1024
                    }
1025

1026
                    $this->processFilePath($inputFile);
×
1027
                }
1028
            } else if (substr($arg, 0, 11) === 'stdin-path=') {
69✔
1029
                if (isset($this->overriddenDefaults['stdinPath']) === true) {
×
1030
                    break;
×
1031
                }
1032

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

1035
                // It may not exist and return false instead, so use whatever they gave us.
1036
                if ($this->stdinPath === false) {
×
1037
                    $this->stdinPath = trim(substr($arg, 11));
×
1038
                }
1039

1040
                $this->overriddenDefaults['stdinPath'] = true;
×
1041
            } else if (PHP_CODESNIFFER_CBF === false && substr($arg, 0, 12) === 'report-file=') {
69✔
1042
                if (isset($this->overriddenDefaults['reportFile']) === true) {
×
1043
                    break;
×
1044
                }
1045

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

1048
                // It may not exist and return false instead.
1049
                if ($this->reportFile === false) {
×
1050
                    $this->reportFile = substr($arg, 12);
×
1051

1052
                    $dir = Common::realpath(dirname($this->reportFile));
×
1053
                    if (is_dir($dir) === false) {
×
1054
                        $error  = 'ERROR: The specified report file path "'.$this->reportFile.'" points to a non-existent directory'.PHP_EOL.PHP_EOL;
×
1055
                        $error .= $this->printShortUsage(true);
×
1056
                        throw new DeepExitException($error, 3);
×
1057
                    }
1058

1059
                    $this->reportFile = $dir.'/'.basename($this->reportFile);
×
1060
                }//end if
1061

1062
                $this->overriddenDefaults['reportFile'] = true;
×
1063

1064
                if (is_dir($this->reportFile) === true) {
×
1065
                    $error  = 'ERROR: The specified report file path "'.$this->reportFile.'" is a directory'.PHP_EOL.PHP_EOL;
×
1066
                    $error .= $this->printShortUsage(true);
×
1067
                    throw new DeepExitException($error, 3);
×
1068
                }
1069
            } else if (substr($arg, 0, 13) === 'report-width=') {
69✔
1070
                if (isset($this->overriddenDefaults['reportWidth']) === true) {
9✔
1071
                    break;
3✔
1072
                }
1073

1074
                $this->reportWidth = substr($arg, 13);
9✔
1075
                $this->overriddenDefaults['reportWidth'] = true;
9✔
1076
            } else if (substr($arg, 0, 9) === 'basepath=') {
69✔
1077
                if (isset($this->overriddenDefaults['basepath']) === true) {
×
1078
                    break;
×
1079
                }
1080

1081
                $this->overriddenDefaults['basepath'] = true;
×
1082

1083
                if (substr($arg, 9) === '') {
×
1084
                    $this->basepath = null;
×
1085
                    break;
×
1086
                }
1087

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

1090
                // It may not exist and return false instead.
1091
                if ($this->basepath === false) {
×
1092
                    $this->basepath = substr($arg, 9);
×
1093
                }
1094

1095
                if (is_dir($this->basepath) === false) {
×
1096
                    $error  = 'ERROR: The specified basepath "'.$this->basepath.'" points to a non-existent directory'.PHP_EOL.PHP_EOL;
×
1097
                    $error .= $this->printShortUsage(true);
×
1098
                    throw new DeepExitException($error, 3);
×
1099
                }
1100
            } else if ((substr($arg, 0, 7) === 'report=' || substr($arg, 0, 7) === 'report-')) {
69✔
1101
                $reports = [];
×
1102

1103
                if ($arg[6] === '-') {
×
1104
                    // This is a report with file output.
1105
                    $split = strpos($arg, '=');
×
1106
                    if ($split === false) {
×
1107
                        $report = substr($arg, 7);
×
1108
                        $output = null;
×
1109
                    } else {
1110
                        $report = substr($arg, 7, ($split - 7));
×
1111
                        $output = substr($arg, ($split + 1));
×
1112
                        if ($output === false) {
×
1113
                            $output = null;
×
1114
                        } else {
1115
                            $dir = Common::realpath(dirname($output));
×
1116
                            if (is_dir($dir) === false) {
×
1117
                                $error  = 'ERROR: The specified '.$report.' report file path "'.$output.'" points to a non-existent directory'.PHP_EOL.PHP_EOL;
×
1118
                                $error .= $this->printShortUsage(true);
×
1119
                                throw new DeepExitException($error, 3);
×
1120
                            }
1121

1122
                            $output = $dir.'/'.basename($output);
×
1123

1124
                            if (is_dir($output) === true) {
×
1125
                                $error  = 'ERROR: The specified '.$report.' report file path "'.$output.'" is a directory'.PHP_EOL.PHP_EOL;
×
1126
                                $error .= $this->printShortUsage(true);
×
1127
                                throw new DeepExitException($error, 3);
×
1128
                            }
1129
                        }//end if
1130
                    }//end if
1131

1132
                    $reports[$report] = $output;
×
1133
                } else {
1134
                    // This is a single report.
1135
                    if (isset($this->overriddenDefaults['reports']) === true) {
×
1136
                        break;
×
1137
                    }
1138

1139
                    $reportNames = explode(',', substr($arg, 7));
×
1140
                    foreach ($reportNames as $report) {
×
1141
                        $reports[$report] = null;
×
1142
                    }
1143
                }//end if
1144

1145
                // Remove the default value so the CLI value overrides it.
1146
                if (isset($this->overriddenDefaults['reports']) === false) {
×
1147
                    $this->reports = $reports;
×
1148
                } else {
1149
                    $this->reports = array_merge($this->reports, $reports);
×
1150
                }
1151

1152
                $this->overriddenDefaults['reports'] = true;
×
1153
            } else if (substr($arg, 0, 7) === 'filter=') {
69✔
1154
                if (isset($this->overriddenDefaults['filter']) === true) {
×
1155
                    break;
×
1156
                }
1157

1158
                $this->filter = substr($arg, 7);
×
1159
                $this->overriddenDefaults['filter'] = true;
×
1160
            } else if (substr($arg, 0, 9) === 'standard=') {
69✔
1161
                $standards = trim(substr($arg, 9));
9✔
1162
                if ($standards !== '') {
9✔
1163
                    $this->standards = explode(',', $standards);
9✔
1164
                }
1165

1166
                $this->overriddenDefaults['standards'] = true;
9✔
1167
            } else if (substr($arg, 0, 11) === 'extensions=') {
60✔
1168
                if (isset($this->overriddenDefaults['extensions']) === true) {
30✔
1169
                    break;
3✔
1170
                }
1171

1172
                $extensionsString = substr($arg, 11);
30✔
1173
                $newExtensions    = [];
30✔
1174
                if (empty($extensionsString) === false) {
30✔
1175
                    $extensions = explode(',', $extensionsString);
27✔
1176
                    foreach ($extensions as $ext) {
27✔
1177
                        if (strpos($ext, '/') !== false) {
27✔
1178
                            // They specified the tokenizer too.
1179
                            list($ext, $tokenizer) = explode('/', $ext);
12✔
1180
                            if (strtoupper($tokenizer) !== 'PHP') {
12✔
1181
                                $error  = 'ERROR: Specifying the tokenizer to use for an extension is no longer supported.'.PHP_EOL;
9✔
1182
                                $error .= 'PHP_CodeSniffer >= 4.0 only supports scanning PHP files.'.PHP_EOL;
9✔
1183
                                $error .= 'Received: '.substr($arg, 11).PHP_EOL.PHP_EOL;
9✔
1184
                                $error .= $this->printShortUsage(true);
9✔
1185
                                throw new DeepExitException($error, 3);
9✔
1186
                            }
1187
                        }
1188

1189
                        $newExtensions[$ext] = 'PHP';
21✔
1190
                    }
1191
                }
1192

1193
                $this->extensions = $newExtensions;
21✔
1194
                $this->overriddenDefaults['extensions'] = true;
21✔
1195
            } else if (substr($arg, 0, 7) === 'suffix=') {
30✔
1196
                if (isset($this->overriddenDefaults['suffix']) === true) {
×
1197
                    break;
×
1198
                }
1199

1200
                $this->suffix = substr($arg, 7);
×
1201
                $this->overriddenDefaults['suffix'] = true;
×
1202
            } else if (substr($arg, 0, 9) === 'parallel=') {
30✔
1203
                if (isset($this->overriddenDefaults['parallel']) === true) {
×
1204
                    break;
×
1205
                }
1206

1207
                $this->parallel = max((int) substr($arg, 9), 1);
×
1208
                $this->overriddenDefaults['parallel'] = true;
×
1209
            } else if (substr($arg, 0, 9) === 'severity=') {
30✔
1210
                $this->errorSeverity   = (int) substr($arg, 9);
×
1211
                $this->warningSeverity = $this->errorSeverity;
×
1212
                if (isset($this->overriddenDefaults['errorSeverity']) === false) {
×
1213
                    $this->overriddenDefaults['errorSeverity'] = true;
×
1214
                }
1215

1216
                if (isset($this->overriddenDefaults['warningSeverity']) === false) {
×
1217
                    $this->overriddenDefaults['warningSeverity'] = true;
×
1218
                }
1219
            } else if (substr($arg, 0, 15) === 'error-severity=') {
30✔
1220
                if (isset($this->overriddenDefaults['errorSeverity']) === true) {
×
1221
                    break;
×
1222
                }
1223

1224
                $this->errorSeverity = (int) substr($arg, 15);
×
1225
                $this->overriddenDefaults['errorSeverity'] = true;
×
1226
            } else if (substr($arg, 0, 17) === 'warning-severity=') {
30✔
1227
                if (isset($this->overriddenDefaults['warningSeverity']) === true) {
×
1228
                    break;
×
1229
                }
1230

1231
                $this->warningSeverity = (int) substr($arg, 17);
×
1232
                $this->overriddenDefaults['warningSeverity'] = true;
×
1233
            } else if (substr($arg, 0, 7) === 'ignore=') {
30✔
1234
                if (isset($this->overriddenDefaults['ignored']) === true) {
×
1235
                    break;
×
1236
                }
1237

1238
                // Split the ignore string on commas, unless the comma is escaped
1239
                // using 1 or 3 slashes (\, or \\\,).
1240
                $patterns = preg_split(
×
1241
                    '/(?<=(?<!\\\\)\\\\\\\\),|(?<!\\\\),/',
×
1242
                    substr($arg, 7)
×
1243
                );
1244

1245
                $ignored = [];
×
1246
                foreach ($patterns as $pattern) {
×
1247
                    $pattern = trim($pattern);
×
1248
                    if ($pattern === '') {
×
1249
                        continue;
×
1250
                    }
1251

1252
                    $ignored[$pattern] = 'absolute';
×
1253
                }
1254

1255
                $this->ignored = $ignored;
×
1256
                $this->overriddenDefaults['ignored'] = true;
×
1257
            } else if (substr($arg, 0, 10) === 'generator='
30✔
1258
                && PHP_CODESNIFFER_CBF === false
30✔
1259
            ) {
1260
                if (isset($this->overriddenDefaults['generator']) === true) {
30✔
1261
                    break;
3✔
1262
                }
1263

1264
                $generatorName          = substr($arg, 10);
30✔
1265
                $lowerCaseGeneratorName = strtolower($generatorName);
30✔
1266

1267
                if (isset($this->validGenerators[$lowerCaseGeneratorName]) === false) {
30✔
1268
                    $validOptions = implode(', ', $this->validGenerators);
9✔
1269
                    $validOptions = substr_replace($validOptions, ' and', strrpos($validOptions, ','), 1);
9✔
1270
                    $error        = sprintf(
9✔
1271
                        'ERROR: "%s" is not a valid generator. The following generators are supported: %s.'.PHP_EOL.PHP_EOL,
9✔
1272
                        $generatorName,
9✔
1273
                        $validOptions
9✔
1274
                    );
6✔
1275
                    $error       .= $this->printShortUsage(true);
9✔
1276
                    throw new DeepExitException($error, 3);
9✔
1277
                }
1278

1279
                $this->generator = $this->validGenerators[$lowerCaseGeneratorName];
21✔
1280
                $this->overriddenDefaults['generator'] = true;
21✔
1281
            } else if (substr($arg, 0, 9) === 'encoding=') {
×
1282
                if (isset($this->overriddenDefaults['encoding']) === true) {
×
1283
                    break;
×
1284
                }
1285

1286
                $this->encoding = strtolower(substr($arg, 9));
×
1287
                $this->overriddenDefaults['encoding'] = true;
×
1288
            } else if (substr($arg, 0, 10) === 'tab-width=') {
×
1289
                if (isset($this->overriddenDefaults['tabWidth']) === true) {
×
1290
                    break;
×
1291
                }
1292

1293
                $this->tabWidth = (int) substr($arg, 10);
×
1294
                $this->overriddenDefaults['tabWidth'] = true;
×
1295
            } else {
1296
                if ($this->dieOnUnknownArg === false) {
×
1297
                    $eqPos = strpos($arg, '=');
×
1298
                    try {
1299
                        $unknown = $this->unknown;
×
1300

1301
                        if ($eqPos === false) {
×
1302
                            $unknown[$arg] = $arg;
×
1303
                        } else {
1304
                            $value         = substr($arg, ($eqPos + 1));
×
1305
                            $arg           = substr($arg, 0, $eqPos);
×
1306
                            $unknown[$arg] = $value;
×
1307
                        }
1308

1309
                        $this->unknown = $unknown;
×
1310
                    } catch (RuntimeException $e) {
×
1311
                        // Value is not valid, so just ignore it.
1312
                    }
1313
                } else {
1314
                    $this->processUnknownArgument('--'.$arg, $pos);
×
1315
                }
1316
            }//end if
1317
            break;
93✔
1318
        }//end switch
1319

1320
    }//end processLongArgument()
31✔
1321

1322

1323
    /**
1324
     * Parse supplied string into a list of validated sniff codes.
1325
     *
1326
     * @param string $input    Comma-separated string of sniff codes.
1327
     * @param string $argument The name of the argument which is being processed.
1328
     *
1329
     * @return array<string>
1330
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException When any of the provided codes are not valid as sniff codes.
1331
     */
1332
    private function parseSniffCodes($input, $argument)
114✔
1333
    {
1334
        $errors = [];
114✔
1335
        $sniffs = [];
114✔
1336

1337
        $possibleSniffs = array_filter(explode(',', $input));
114✔
1338

1339
        if ($possibleSniffs === []) {
114✔
1340
            $errors[] = 'No codes specified / empty argument';
18✔
1341
        }
1342

1343
        foreach ($possibleSniffs as $sniff) {
114✔
1344
            $sniff = trim($sniff);
96✔
1345

1346
            $partCount = substr_count($sniff, '.');
96✔
1347
            if ($partCount === 2) {
96✔
1348
                // Correct number of parts.
1349
                $sniffs[] = $sniff;
54✔
1350
                continue;
54✔
1351
            }
1352

1353
            if ($partCount === 0) {
54✔
1354
                $errors[] = 'Standard codes are not supported: '.$sniff;
12✔
1355
            } else if ($partCount === 1) {
42✔
1356
                $errors[] = 'Category codes are not supported: '.$sniff;
18✔
1357
            } else if ($partCount === 3) {
24✔
1358
                $errors[] = 'Message codes are not supported: '.$sniff;
18✔
1359
            } else {
1360
                $errors[] = 'Too many parts: '.$sniff;
12✔
1361
            }
1362

1363
            if ($partCount > 2) {
54✔
1364
                $parts    = explode('.', $sniff, 4);
24✔
1365
                $sniffs[] = $parts[0].'.'.$parts[1].'.'.$parts[2];
24✔
1366
            }
1367
        }//end foreach
1368

1369
        $sniffs = array_reduce(
114✔
1370
            $sniffs,
114✔
1371
            static function ($carry, $item) {
76✔
1372
                $lower = strtolower($item);
78✔
1373

1374
                foreach ($carry as $found) {
78✔
1375
                    if ($lower === strtolower($found)) {
36✔
1376
                        // This sniff is already in our list.
1377
                        return $carry;
24✔
1378
                    }
1379
                }
1380

1381
                $carry[] = $item;
78✔
1382

1383
                return $carry;
78✔
1384
            },
114✔
1385
            []
114✔
1386
        );
76✔
1387

1388
        if ($errors !== []) {
114✔
1389
            $error  = 'ERROR: The --'.$argument.' option only supports sniff codes.'.PHP_EOL;
72✔
1390
            $error .= 'Sniff codes are in the form "Standard.Category.Sniff".'.PHP_EOL;
72✔
1391
            $error .= PHP_EOL;
72✔
1392
            $error .= 'The following problems were detected:'.PHP_EOL;
72✔
1393
            $error .= '* '.implode(PHP_EOL.'* ', $errors).PHP_EOL;
72✔
1394

1395
            if ($sniffs !== []) {
72✔
1396
                $error .= PHP_EOL;
36✔
1397
                $error .= 'Perhaps try --'.$argument.'="'.implode(',', $sniffs).'" instead.'.PHP_EOL;
36✔
1398
            }
1399

1400
            $error .= PHP_EOL;
72✔
1401
            $error .= $this->printShortUsage(true);
72✔
1402
            throw new DeepExitException(ltrim($error), 3);
72✔
1403
        }
1404

1405
        return $sniffs;
42✔
1406

1407
    }//end parseSniffCodes()
1408

1409

1410
    /**
1411
     * Processes an unknown command line argument.
1412
     *
1413
     * Assumes all unknown arguments are files and folders to check.
1414
     *
1415
     * @param string $arg The command line argument.
1416
     * @param int    $pos The position of the argument on the command line.
1417
     *
1418
     * @return void
1419
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
1420
     */
1421
    public function processUnknownArgument($arg, $pos)
×
1422
    {
1423
        // We don't know about any additional switches; just files.
1424
        if ($arg[0] === '-') {
×
1425
            if ($this->dieOnUnknownArg === false) {
×
1426
                return;
×
1427
            }
1428

1429
            $error  = "ERROR: option \"$arg\" not known".PHP_EOL.PHP_EOL;
×
1430
            $error .= $this->printShortUsage(true);
×
1431
            throw new DeepExitException($error, 3);
×
1432
        }
1433

1434
        $this->processFilePath($arg);
×
1435

1436
    }//end processUnknownArgument()
1437

1438

1439
    /**
1440
     * Processes a file path and add it to the file list.
1441
     *
1442
     * @param string $path The path to the file to add.
1443
     *
1444
     * @return void
1445
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
1446
     */
1447
    public function processFilePath($path)
×
1448
    {
1449
        // If we are processing STDIN, don't record any files to check.
1450
        if ($this->stdin === true) {
×
1451
            return;
×
1452
        }
1453

1454
        $file = Common::realpath($path);
×
1455
        if (file_exists($file) === false) {
×
1456
            if ($this->dieOnUnknownArg === false) {
×
1457
                return;
×
1458
            }
1459

1460
            $error  = 'ERROR: The file "'.$path.'" does not exist.'.PHP_EOL.PHP_EOL;
×
1461
            $error .= $this->printShortUsage(true);
×
1462
            throw new DeepExitException($error, 3);
×
1463
        } else {
1464
            // Can't modify the files array directly because it's not a real
1465
            // class member, so need to use this little get/modify/set trick.
1466
            $files       = $this->files;
×
1467
            $files[]     = $file;
×
1468
            $this->files = $files;
×
1469
            $this->overriddenDefaults['files'] = true;
×
1470
        }
1471

1472
    }//end processFilePath()
1473

1474

1475
    /**
1476
     * Prints out the usage information for this script.
1477
     *
1478
     * @return void
1479
     */
1480
    public function printUsage()
×
1481
    {
1482
        echo PHP_EOL;
×
1483

1484
        if (PHP_CODESNIFFER_CBF === true) {
×
1485
            $this->printPHPCBFUsage();
×
1486
        } else {
1487
            $this->printPHPCSUsage();
×
1488
        }
1489

1490
        echo PHP_EOL;
×
1491

1492
    }//end printUsage()
1493

1494

1495
    /**
1496
     * Prints out the short usage information for this script.
1497
     *
1498
     * @param bool $return If TRUE, the usage string is returned
1499
     *                     instead of output to screen.
1500
     *
1501
     * @return string|void
1502
     */
1503
    public function printShortUsage($return=false)
×
1504
    {
1505
        if (PHP_CODESNIFFER_CBF === true) {
×
1506
            $usage = 'Run "phpcbf --help" for usage information';
×
1507
        } else {
1508
            $usage = 'Run "phpcs --help" for usage information';
×
1509
        }
1510

1511
        $usage .= PHP_EOL.PHP_EOL;
×
1512

1513
        if ($return === true) {
×
1514
            return $usage;
×
1515
        }
1516

1517
        echo $usage;
×
1518

1519
    }//end printShortUsage()
1520

1521

1522
    /**
1523
     * Prints out the usage information for PHPCS.
1524
     *
1525
     * @return void
1526
     */
1527
    public function printPHPCSUsage()
×
1528
    {
1529
        $longOptions   = explode(',', Help::DEFAULT_LONG_OPTIONS);
×
1530
        $longOptions[] = 'cache';
×
1531
        $longOptions[] = 'no-cache';
×
1532
        $longOptions[] = 'report';
×
1533
        $longOptions[] = 'report-file';
×
1534
        $longOptions[] = 'report-report';
×
1535
        $longOptions[] = 'config-explain';
×
1536
        $longOptions[] = 'config-set';
×
1537
        $longOptions[] = 'config-delete';
×
1538
        $longOptions[] = 'config-show';
×
1539
        $longOptions[] = 'generator';
×
1540

1541
        $shortOptions = Help::DEFAULT_SHORT_OPTIONS.'aems';
×
1542

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

1545
    }//end printPHPCSUsage()
1546

1547

1548
    /**
1549
     * Prints out the usage information for PHPCBF.
1550
     *
1551
     * @return void
1552
     */
1553
    public function printPHPCBFUsage()
×
1554
    {
1555
        $longOptions   = explode(',', Help::DEFAULT_LONG_OPTIONS);
×
1556
        $longOptions[] = 'suffix';
×
1557
        $shortOptions  = Help::DEFAULT_SHORT_OPTIONS;
×
1558

1559
        (new Help($this, $longOptions, $shortOptions))->display();
×
1560

1561
    }//end printPHPCBFUsage()
1562

1563

1564
    /**
1565
     * Get a single config value.
1566
     *
1567
     * @param string $key The name of the config value.
1568
     *
1569
     * @return string|null
1570
     * @see    setConfigData()
1571
     * @see    getAllConfigData()
1572
     */
1573
    public static function getConfigData($key)
6✔
1574
    {
1575
        $phpCodeSnifferConfig = self::getAllConfigData();
6✔
1576

1577
        if ($phpCodeSnifferConfig === null) {
6✔
1578
            return null;
×
1579
        }
1580

1581
        if (isset($phpCodeSnifferConfig[$key]) === false) {
6✔
1582
            return null;
6✔
1583
        }
1584

1585
        return $phpCodeSnifferConfig[$key];
6✔
1586

1587
    }//end getConfigData()
1588

1589

1590
    /**
1591
     * Get the path to an executable utility.
1592
     *
1593
     * @param string $name The name of the executable utility.
1594
     *
1595
     * @return string|null
1596
     * @see    getConfigData()
1597
     */
1598
    public static function getExecutablePath($name)
×
1599
    {
1600
        $data = self::getConfigData($name.'_path');
×
1601
        if ($data !== null) {
×
1602
            return $data;
×
1603
        }
1604

1605
        if ($name === "php") {
×
1606
            // For php, we know the executable path. There's no need to look it up.
1607
            return PHP_BINARY;
×
1608
        }
1609

1610
        if (array_key_exists($name, self::$executablePaths) === true) {
×
1611
            return self::$executablePaths[$name];
×
1612
        }
1613

1614
        if (PHP_OS_FAMILY === 'Windows') {
×
1615
            $cmd = 'where '.escapeshellarg($name).' 2> nul';
×
1616
        } else {
1617
            $cmd = 'which '.escapeshellarg($name).' 2> /dev/null';
×
1618
        }
1619

1620
        $result = exec($cmd, $output, $retVal);
×
1621
        if ($retVal !== 0) {
×
1622
            $result = null;
×
1623
        }
1624

1625
        self::$executablePaths[$name] = $result;
×
1626
        return $result;
×
1627

1628
    }//end getExecutablePath()
1629

1630

1631
    /**
1632
     * Set a single config value.
1633
     *
1634
     * @param string      $key   The name of the config value.
1635
     * @param string|null $value The value to set. If null, the config
1636
     *                           entry is deleted, reverting it to the
1637
     *                           default value.
1638
     * @param boolean     $temp  Set this config data temporarily for this
1639
     *                           script run. This will not write the config
1640
     *                           data to the config file.
1641
     *
1642
     * @return bool
1643
     * @see    getConfigData()
1644
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the config file can not be written.
1645
     */
1646
    public function setConfigData($key, $value, $temp=false)
×
1647
    {
1648
        if (isset($this->overriddenDefaults['runtime-set']) === true
×
1649
            && isset($this->overriddenDefaults['runtime-set'][$key]) === true
×
1650
        ) {
1651
            return false;
×
1652
        }
1653

1654
        if ($temp === false) {
×
1655
            $path = '';
×
1656
            if (is_callable('\Phar::running') === true) {
×
1657
                $path = Phar::running(false);
×
1658
            }
1659

1660
            if ($path !== '') {
×
1661
                $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1662
            } else {
1663
                $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1664
            }
1665

1666
            if (is_file($configFile) === true
×
1667
                && is_writable($configFile) === false
×
1668
            ) {
1669
                $error = 'ERROR: Config file '.$configFile.' is not writable'.PHP_EOL.PHP_EOL;
×
1670
                throw new DeepExitException($error, 3);
×
1671
            }
1672
        }//end if
1673

1674
        $phpCodeSnifferConfig = self::getAllConfigData();
×
1675

1676
        if ($value === null) {
×
1677
            if (isset($phpCodeSnifferConfig[$key]) === true) {
×
1678
                unset($phpCodeSnifferConfig[$key]);
×
1679
            }
1680
        } else {
1681
            $phpCodeSnifferConfig[$key] = $value;
×
1682
        }
1683

1684
        if ($temp === false) {
×
1685
            $output  = '<'.'?php'."\n".' $phpCodeSnifferConfig = ';
×
1686
            $output .= var_export($phpCodeSnifferConfig, true);
×
1687
            $output .= ";\n?".'>';
×
1688

1689
            if (file_put_contents($configFile, $output) === false) {
×
1690
                $error = 'ERROR: Config file '.$configFile.' could not be written'.PHP_EOL.PHP_EOL;
×
1691
                throw new DeepExitException($error, 3);
×
1692
            }
1693

1694
            self::$configDataFile = $configFile;
×
1695
        }
1696

1697
        self::$configData = $phpCodeSnifferConfig;
×
1698

1699
        // If the installed paths are being set, make sure all known
1700
        // standards paths are added to the autoloader.
1701
        if ($key === 'installed_paths') {
×
1702
            $installedStandards = Standards::getInstalledStandardDetails();
×
1703
            foreach ($installedStandards as $details) {
×
1704
                Autoload::addSearchPath($details['path'], $details['namespace']);
×
1705
            }
1706
        }
1707

1708
        return true;
×
1709

1710
    }//end setConfigData()
1711

1712

1713
    /**
1714
     * Get all config data.
1715
     *
1716
     * @return array<string, string>
1717
     * @see    getConfigData()
1718
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the config file could not be read.
1719
     */
1720
    public static function getAllConfigData()
×
1721
    {
1722
        if (self::$configData !== null) {
×
1723
            return self::$configData;
×
1724
        }
1725

1726
        $path = '';
×
1727
        if (is_callable('\Phar::running') === true) {
×
1728
            $path = Phar::running(false);
×
1729
        }
1730

1731
        if ($path !== '') {
×
1732
            $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1733
        } else {
1734
            $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1735
            if (is_file($configFile) === false
×
1736
                && strpos('@data_dir@', '@data_dir') === false
×
1737
            ) {
1738
                $configFile = '@data_dir@/PHP_CodeSniffer/CodeSniffer.conf';
×
1739
            }
1740
        }
1741

1742
        if (is_file($configFile) === false) {
×
1743
            self::$configData = [];
×
1744
            return [];
×
1745
        }
1746

1747
        if (Common::isReadable($configFile) === false) {
×
1748
            $error = 'ERROR: Config file '.$configFile.' is not readable'.PHP_EOL.PHP_EOL;
×
1749
            throw new DeepExitException($error, 3);
×
1750
        }
1751

1752
        include $configFile;
×
1753
        self::$configDataFile = $configFile;
×
1754
        self::$configData     = $phpCodeSnifferConfig;
×
1755
        return self::$configData;
×
1756

1757
    }//end getAllConfigData()
1758

1759

1760
    /**
1761
     * Prints out the gathered config data.
1762
     *
1763
     * @param array $data The config data to print.
1764
     *
1765
     * @return void
1766
     */
1767
    public function printConfigData($data)
×
1768
    {
1769
        $max  = 0;
×
1770
        $keys = array_keys($data);
×
1771
        foreach ($keys as $key) {
×
1772
            $len = strlen($key);
×
1773
            if (strlen($key) > $max) {
×
1774
                $max = $len;
×
1775
            }
1776
        }
1777

1778
        if ($max === 0) {
×
1779
            return;
×
1780
        }
1781

1782
        $max += 2;
×
1783
        ksort($data);
×
1784
        foreach ($data as $name => $value) {
×
1785
            echo str_pad($name.': ', $max).$value.PHP_EOL;
×
1786
        }
1787

1788
    }//end printConfigData()
1789

1790

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