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

PHPCSStandards / PHP_CodeSniffer / 14732903196

29 Apr 2025 01:48PM UTC coverage: 78.485% (+0.02%) from 78.466%
14732903196

push

github

web-flow
Merge pull request #1056 from PHPCSStandards/phpcs-4.0/feature/remove-more-output-buffering-from-config-2

Config: remove some more output buffering

0 of 2 new or added lines in 1 file covered. (0.0%)

19564 of 24927 relevant lines covered (78.49%)

86.21 hits per line

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

36.46
/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
            $this->printUsage();
×
NEW
683
            throw new DeepExitException('', 0);
×
684
        case 'i' :
29✔
685
            $output = Standards::prepareInstalledStandardsForDisplay().PHP_EOL;
×
686
            throw new DeepExitException($output, 0);
×
687
        case 'v' :
29✔
688
            if ($this->quiet === true) {
×
689
                // Ignore when quiet mode is enabled.
690
                break;
×
691
            }
692

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

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

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

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

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

777
    }//end processShortArgument()
5✔
778

779

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

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

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

820
            if (defined('PHP_CODESNIFFER_IN_TESTS') === false) {
×
821
                $this->cache = true;
×
822
                $this->overriddenDefaults['cache'] = true;
×
823
            }
824
            break;
×
825
        case 'no-cache':
183✔
826
            if (isset($this->overriddenDefaults['cache']) === true) {
×
827
                break;
×
828
            }
829

830
            $this->cache = false;
×
831
            $this->overriddenDefaults['cache'] = true;
×
832
            break;
×
833
        case 'ignore-annotations':
183✔
834
            if (isset($this->overriddenDefaults['annotations']) === true) {
×
835
                break;
×
836
            }
837

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

850
            $key     = $this->cliArgs[($pos + 1)];
×
851
            $value   = $this->cliArgs[($pos + 2)];
×
852
            $current = self::getConfigData($key);
×
853

854
            try {
855
                $this->setConfigData($key, $value);
×
856
            } catch (Exception $e) {
×
857
                throw new DeepExitException($e->getMessage().PHP_EOL, 3);
×
858
            }
859

860
            $output = 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL;
×
861

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

875
            $output = 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL;
×
876

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

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

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

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

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

929
                $this->exclude = $this->parseSniffCodes(substr($arg, 8), 'exclude');
57✔
930
                $this->overriddenDefaults['exclude'] = true;
21✔
931
            } else if (defined('PHP_CODESNIFFER_IN_TESTS') === false
69✔
932
                && substr($arg, 0, 6) === 'cache='
69✔
933
            ) {
934
                if ((isset($this->overriddenDefaults['cache']) === true
×
935
                    && $this->cache === false)
×
936
                    || isset($this->overriddenDefaults['cacheFile']) === true
×
937
                ) {
938
                    break;
×
939
                }
940

941
                // Turn caching on.
942
                $this->cache = true;
×
943
                $this->overriddenDefaults['cache'] = true;
×
944

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

947
                // It may not exist and return false instead.
948
                if ($this->cacheFile === false) {
×
949
                    $this->cacheFile = substr($arg, 6);
×
950

951
                    $dir = dirname($this->cacheFile);
×
952
                    if (is_dir($dir) === false) {
×
953
                        $error  = 'ERROR: The specified cache file path "'.$this->cacheFile.'" points to a non-existent directory'.PHP_EOL.PHP_EOL;
×
954
                        $error .= $this->printShortUsage(true);
×
955
                        throw new DeepExitException($error, 3);
×
956
                    }
957

958
                    if ($dir === '.') {
×
959
                        // Passed cache file is a file in the current directory.
960
                        $this->cacheFile = getcwd().'/'.basename($this->cacheFile);
×
961
                    } else {
962
                        if ($dir[0] === '/') {
×
963
                            // An absolute path.
964
                            $dir = Common::realpath($dir);
×
965
                        } else {
966
                            $dir = Common::realpath(getcwd().'/'.$dir);
×
967
                        }
968

969
                        if ($dir !== false) {
×
970
                            // Cache file path is relative.
971
                            $this->cacheFile = $dir.'/'.basename($this->cacheFile);
×
972
                        }
973
                    }
974
                }//end if
975

976
                $this->overriddenDefaults['cacheFile'] = true;
×
977

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

994
                    $bootstrap[] = $path;
×
995
                }
996

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

1008
                $files = file($path);
×
1009
                foreach ($files as $inputFile) {
×
1010
                    $inputFile = trim($inputFile);
×
1011

1012
                    // Skip empty lines.
1013
                    if ($inputFile === '') {
×
1014
                        continue;
×
1015
                    }
1016

1017
                    $this->processFilePath($inputFile);
×
1018
                }
1019
            } else if (substr($arg, 0, 11) === 'stdin-path=') {
69✔
1020
                if (isset($this->overriddenDefaults['stdinPath']) === true) {
×
1021
                    break;
×
1022
                }
1023

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

1026
                // It may not exist and return false instead, so use whatever they gave us.
1027
                if ($this->stdinPath === false) {
×
1028
                    $this->stdinPath = trim(substr($arg, 11));
×
1029
                }
1030

1031
                $this->overriddenDefaults['stdinPath'] = true;
×
1032
            } else if (PHP_CODESNIFFER_CBF === false && substr($arg, 0, 12) === 'report-file=') {
69✔
1033
                if (isset($this->overriddenDefaults['reportFile']) === true) {
×
1034
                    break;
×
1035
                }
1036

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

1039
                // It may not exist and return false instead.
1040
                if ($this->reportFile === false) {
×
1041
                    $this->reportFile = substr($arg, 12);
×
1042

1043
                    $dir = Common::realpath(dirname($this->reportFile));
×
1044
                    if (is_dir($dir) === false) {
×
1045
                        $error  = 'ERROR: The specified report file path "'.$this->reportFile.'" points to a non-existent directory'.PHP_EOL.PHP_EOL;
×
1046
                        $error .= $this->printShortUsage(true);
×
1047
                        throw new DeepExitException($error, 3);
×
1048
                    }
1049

1050
                    $this->reportFile = $dir.'/'.basename($this->reportFile);
×
1051
                }//end if
1052

1053
                $this->overriddenDefaults['reportFile'] = true;
×
1054

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

1065
                $this->reportWidth = substr($arg, 13);
9✔
1066
                $this->overriddenDefaults['reportWidth'] = true;
9✔
1067
            } else if (substr($arg, 0, 9) === 'basepath=') {
69✔
1068
                if (isset($this->overriddenDefaults['basepath']) === true) {
×
1069
                    break;
×
1070
                }
1071

1072
                $this->overriddenDefaults['basepath'] = true;
×
1073

1074
                if (substr($arg, 9) === '') {
×
1075
                    $this->basepath = null;
×
1076
                    break;
×
1077
                }
1078

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

1081
                // It may not exist and return false instead.
1082
                if ($this->basepath === false) {
×
1083
                    $this->basepath = substr($arg, 9);
×
1084
                }
1085

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

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

1113
                            $output = $dir.'/'.basename($output);
×
1114

1115
                            if (is_dir($output) === true) {
×
1116
                                $error  = 'ERROR: The specified '.$report.' report file path "'.$output.'" is a directory'.PHP_EOL.PHP_EOL;
×
1117
                                $error .= $this->printShortUsage(true);
×
1118
                                throw new DeepExitException($error, 3);
×
1119
                            }
1120
                        }//end if
1121
                    }//end if
1122

1123
                    $reports[$report] = $output;
×
1124
                } else {
1125
                    // This is a single report.
1126
                    if (isset($this->overriddenDefaults['reports']) === true) {
×
1127
                        break;
×
1128
                    }
1129

1130
                    $reportNames = explode(',', substr($arg, 7));
×
1131
                    foreach ($reportNames as $report) {
×
1132
                        $reports[$report] = null;
×
1133
                    }
1134
                }//end if
1135

1136
                // Remove the default value so the CLI value overrides it.
1137
                if (isset($this->overriddenDefaults['reports']) === false) {
×
1138
                    $this->reports = $reports;
×
1139
                } else {
1140
                    $this->reports = array_merge($this->reports, $reports);
×
1141
                }
1142

1143
                $this->overriddenDefaults['reports'] = true;
×
1144
            } else if (substr($arg, 0, 7) === 'filter=') {
69✔
1145
                if (isset($this->overriddenDefaults['filter']) === true) {
×
1146
                    break;
×
1147
                }
1148

1149
                $this->filter = substr($arg, 7);
×
1150
                $this->overriddenDefaults['filter'] = true;
×
1151
            } else if (substr($arg, 0, 9) === 'standard=') {
69✔
1152
                $standards = trim(substr($arg, 9));
9✔
1153
                if ($standards !== '') {
9✔
1154
                    $this->standards = explode(',', $standards);
9✔
1155
                }
1156

1157
                $this->overriddenDefaults['standards'] = true;
9✔
1158
            } else if (substr($arg, 0, 11) === 'extensions=') {
60✔
1159
                if (isset($this->overriddenDefaults['extensions']) === true) {
30✔
1160
                    break;
3✔
1161
                }
1162

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

1180
                        $newExtensions[$ext] = 'PHP';
21✔
1181
                    }
1182
                }
1183

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

1191
                $this->suffix = substr($arg, 7);
×
1192
                $this->overriddenDefaults['suffix'] = true;
×
1193
            } else if (substr($arg, 0, 9) === 'parallel=') {
30✔
1194
                if (isset($this->overriddenDefaults['parallel']) === true) {
×
1195
                    break;
×
1196
                }
1197

1198
                $this->parallel = max((int) substr($arg, 9), 1);
×
1199
                $this->overriddenDefaults['parallel'] = true;
×
1200
            } else if (substr($arg, 0, 9) === 'severity=') {
30✔
1201
                $this->errorSeverity   = (int) substr($arg, 9);
×
1202
                $this->warningSeverity = $this->errorSeverity;
×
1203
                if (isset($this->overriddenDefaults['errorSeverity']) === false) {
×
1204
                    $this->overriddenDefaults['errorSeverity'] = true;
×
1205
                }
1206

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

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

1222
                $this->warningSeverity = (int) substr($arg, 17);
×
1223
                $this->overriddenDefaults['warningSeverity'] = true;
×
1224
            } else if (substr($arg, 0, 7) === 'ignore=') {
30✔
1225
                if (isset($this->overriddenDefaults['ignored']) === true) {
×
1226
                    break;
×
1227
                }
1228

1229
                // Split the ignore string on commas, unless the comma is escaped
1230
                // using 1 or 3 slashes (\, or \\\,).
1231
                $patterns = preg_split(
×
1232
                    '/(?<=(?<!\\\\)\\\\\\\\),|(?<!\\\\),/',
×
1233
                    substr($arg, 7)
×
1234
                );
1235

1236
                $ignored = [];
×
1237
                foreach ($patterns as $pattern) {
×
1238
                    $pattern = trim($pattern);
×
1239
                    if ($pattern === '') {
×
1240
                        continue;
×
1241
                    }
1242

1243
                    $ignored[$pattern] = 'absolute';
×
1244
                }
1245

1246
                $this->ignored = $ignored;
×
1247
                $this->overriddenDefaults['ignored'] = true;
×
1248
            } else if (substr($arg, 0, 10) === 'generator='
30✔
1249
                && PHP_CODESNIFFER_CBF === false
30✔
1250
            ) {
1251
                if (isset($this->overriddenDefaults['generator']) === true) {
30✔
1252
                    break;
3✔
1253
                }
1254

1255
                $generatorName          = substr($arg, 10);
30✔
1256
                $lowerCaseGeneratorName = strtolower($generatorName);
30✔
1257

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

1270
                $this->generator = $this->validGenerators[$lowerCaseGeneratorName];
21✔
1271
                $this->overriddenDefaults['generator'] = true;
21✔
1272
            } else if (substr($arg, 0, 9) === 'encoding=') {
×
1273
                if (isset($this->overriddenDefaults['encoding']) === true) {
×
1274
                    break;
×
1275
                }
1276

1277
                $this->encoding = strtolower(substr($arg, 9));
×
1278
                $this->overriddenDefaults['encoding'] = true;
×
1279
            } else if (substr($arg, 0, 10) === 'tab-width=') {
×
1280
                if (isset($this->overriddenDefaults['tabWidth']) === true) {
×
1281
                    break;
×
1282
                }
1283

1284
                $this->tabWidth = (int) substr($arg, 10);
×
1285
                $this->overriddenDefaults['tabWidth'] = true;
×
1286
            } else {
1287
                if ($this->dieOnUnknownArg === false) {
×
1288
                    $eqPos = strpos($arg, '=');
×
1289
                    try {
1290
                        $unknown = $this->unknown;
×
1291

1292
                        if ($eqPos === false) {
×
1293
                            $unknown[$arg] = $arg;
×
1294
                        } else {
1295
                            $value         = substr($arg, ($eqPos + 1));
×
1296
                            $arg           = substr($arg, 0, $eqPos);
×
1297
                            $unknown[$arg] = $value;
×
1298
                        }
1299

1300
                        $this->unknown = $unknown;
×
1301
                    } catch (RuntimeException $e) {
×
1302
                        // Value is not valid, so just ignore it.
1303
                    }
1304
                } else {
1305
                    $this->processUnknownArgument('--'.$arg, $pos);
×
1306
                }
1307
            }//end if
1308
            break;
93✔
1309
        }//end switch
1310

1311
    }//end processLongArgument()
31✔
1312

1313

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

1328
        $possibleSniffs = array_filter(explode(',', $input));
114✔
1329

1330
        if ($possibleSniffs === []) {
114✔
1331
            $errors[] = 'No codes specified / empty argument';
18✔
1332
        }
1333

1334
        foreach ($possibleSniffs as $sniff) {
114✔
1335
            $sniff = trim($sniff);
96✔
1336

1337
            $partCount = substr_count($sniff, '.');
96✔
1338
            if ($partCount === 2) {
96✔
1339
                // Correct number of parts.
1340
                $sniffs[] = $sniff;
54✔
1341
                continue;
54✔
1342
            }
1343

1344
            if ($partCount === 0) {
54✔
1345
                $errors[] = 'Standard codes are not supported: '.$sniff;
12✔
1346
            } else if ($partCount === 1) {
42✔
1347
                $errors[] = 'Category codes are not supported: '.$sniff;
18✔
1348
            } else if ($partCount === 3) {
24✔
1349
                $errors[] = 'Message codes are not supported: '.$sniff;
18✔
1350
            } else {
1351
                $errors[] = 'Too many parts: '.$sniff;
12✔
1352
            }
1353

1354
            if ($partCount > 2) {
54✔
1355
                $parts    = explode('.', $sniff, 4);
24✔
1356
                $sniffs[] = $parts[0].'.'.$parts[1].'.'.$parts[2];
24✔
1357
            }
1358
        }//end foreach
1359

1360
        $sniffs = array_reduce(
114✔
1361
            $sniffs,
114✔
1362
            static function ($carry, $item) {
76✔
1363
                $lower = strtolower($item);
78✔
1364

1365
                foreach ($carry as $found) {
78✔
1366
                    if ($lower === strtolower($found)) {
36✔
1367
                        // This sniff is already in our list.
1368
                        return $carry;
24✔
1369
                    }
1370
                }
1371

1372
                $carry[] = $item;
78✔
1373

1374
                return $carry;
78✔
1375
            },
114✔
1376
            []
114✔
1377
        );
76✔
1378

1379
        if ($errors !== []) {
114✔
1380
            $error  = 'ERROR: The --'.$argument.' option only supports sniff codes.'.PHP_EOL;
72✔
1381
            $error .= 'Sniff codes are in the form "Standard.Category.Sniff".'.PHP_EOL;
72✔
1382
            $error .= PHP_EOL;
72✔
1383
            $error .= 'The following problems were detected:'.PHP_EOL;
72✔
1384
            $error .= '* '.implode(PHP_EOL.'* ', $errors).PHP_EOL;
72✔
1385

1386
            if ($sniffs !== []) {
72✔
1387
                $error .= PHP_EOL;
36✔
1388
                $error .= 'Perhaps try --'.$argument.'="'.implode(',', $sniffs).'" instead.'.PHP_EOL;
36✔
1389
            }
1390

1391
            $error .= PHP_EOL;
72✔
1392
            $error .= $this->printShortUsage(true);
72✔
1393
            throw new DeepExitException(ltrim($error), 3);
72✔
1394
        }
1395

1396
        return $sniffs;
42✔
1397

1398
    }//end parseSniffCodes()
1399

1400

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

1420
            $error  = "ERROR: option \"$arg\" not known".PHP_EOL.PHP_EOL;
×
1421
            $error .= $this->printShortUsage(true);
×
1422
            throw new DeepExitException($error, 3);
×
1423
        }
1424

1425
        $this->processFilePath($arg);
×
1426

1427
    }//end processUnknownArgument()
1428

1429

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

1445
        $file = Common::realpath($path);
×
1446
        if (file_exists($file) === false) {
×
1447
            if ($this->dieOnUnknownArg === false) {
×
1448
                return;
×
1449
            }
1450

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

1463
    }//end processFilePath()
1464

1465

1466
    /**
1467
     * Prints out the usage information for this script.
1468
     *
1469
     * @return void
1470
     */
1471
    public function printUsage()
×
1472
    {
1473
        echo PHP_EOL;
×
1474

1475
        if (PHP_CODESNIFFER_CBF === true) {
×
1476
            $this->printPHPCBFUsage();
×
1477
        } else {
1478
            $this->printPHPCSUsage();
×
1479
        }
1480

1481
        echo PHP_EOL;
×
1482

1483
    }//end printUsage()
1484

1485

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

1502
        $usage .= PHP_EOL.PHP_EOL;
×
1503

1504
        if ($return === true) {
×
1505
            return $usage;
×
1506
        }
1507

1508
        echo $usage;
×
1509

1510
    }//end printShortUsage()
1511

1512

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

1532
        $shortOptions = Help::DEFAULT_SHORT_OPTIONS.'aems';
×
1533

1534
        (new Help($this, $longOptions, $shortOptions))->display();
×
1535

1536
    }//end printPHPCSUsage()
1537

1538

1539
    /**
1540
     * Prints out the usage information for PHPCBF.
1541
     *
1542
     * @return void
1543
     */
1544
    public function printPHPCBFUsage()
×
1545
    {
1546
        $longOptions   = explode(',', Help::DEFAULT_LONG_OPTIONS);
×
1547
        $longOptions[] = 'suffix';
×
1548
        $shortOptions  = Help::DEFAULT_SHORT_OPTIONS;
×
1549

1550
        (new Help($this, $longOptions, $shortOptions))->display();
×
1551

1552
    }//end printPHPCBFUsage()
1553

1554

1555
    /**
1556
     * Get a single config value.
1557
     *
1558
     * @param string $key The name of the config value.
1559
     *
1560
     * @return string|null
1561
     * @see    setConfigData()
1562
     * @see    getAllConfigData()
1563
     */
1564
    public static function getConfigData($key)
6✔
1565
    {
1566
        $phpCodeSnifferConfig = self::getAllConfigData();
6✔
1567

1568
        if ($phpCodeSnifferConfig === null) {
6✔
1569
            return null;
×
1570
        }
1571

1572
        if (isset($phpCodeSnifferConfig[$key]) === false) {
6✔
1573
            return null;
6✔
1574
        }
1575

1576
        return $phpCodeSnifferConfig[$key];
6✔
1577

1578
    }//end getConfigData()
1579

1580

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

1596
        if ($name === "php") {
×
1597
            // For php, we know the executable path. There's no need to look it up.
1598
            return PHP_BINARY;
×
1599
        }
1600

1601
        if (array_key_exists($name, self::$executablePaths) === true) {
×
1602
            return self::$executablePaths[$name];
×
1603
        }
1604

1605
        if (PHP_OS_FAMILY === 'Windows') {
×
1606
            $cmd = 'where '.escapeshellarg($name).' 2> nul';
×
1607
        } else {
1608
            $cmd = 'which '.escapeshellarg($name).' 2> /dev/null';
×
1609
        }
1610

1611
        $result = exec($cmd, $output, $retVal);
×
1612
        if ($retVal !== 0) {
×
1613
            $result = null;
×
1614
        }
1615

1616
        self::$executablePaths[$name] = $result;
×
1617
        return $result;
×
1618

1619
    }//end getExecutablePath()
1620

1621

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

1645
        if ($temp === false) {
×
1646
            $path = '';
×
1647
            if (is_callable('\Phar::running') === true) {
×
1648
                $path = Phar::running(false);
×
1649
            }
1650

1651
            if ($path !== '') {
×
1652
                $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1653
            } else {
1654
                $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1655
            }
1656

1657
            if (is_file($configFile) === true
×
1658
                && is_writable($configFile) === false
×
1659
            ) {
1660
                $error = 'ERROR: Config file '.$configFile.' is not writable'.PHP_EOL.PHP_EOL;
×
1661
                throw new DeepExitException($error, 3);
×
1662
            }
1663
        }//end if
1664

1665
        $phpCodeSnifferConfig = self::getAllConfigData();
×
1666

1667
        if ($value === null) {
×
1668
            if (isset($phpCodeSnifferConfig[$key]) === true) {
×
1669
                unset($phpCodeSnifferConfig[$key]);
×
1670
            }
1671
        } else {
1672
            $phpCodeSnifferConfig[$key] = $value;
×
1673
        }
1674

1675
        if ($temp === false) {
×
1676
            $output  = '<'.'?php'."\n".' $phpCodeSnifferConfig = ';
×
1677
            $output .= var_export($phpCodeSnifferConfig, true);
×
1678
            $output .= ";\n?".'>';
×
1679

1680
            if (file_put_contents($configFile, $output) === false) {
×
1681
                $error = 'ERROR: Config file '.$configFile.' could not be written'.PHP_EOL.PHP_EOL;
×
1682
                throw new DeepExitException($error, 3);
×
1683
            }
1684

1685
            self::$configDataFile = $configFile;
×
1686
        }
1687

1688
        self::$configData = $phpCodeSnifferConfig;
×
1689

1690
        // If the installed paths are being set, make sure all known
1691
        // standards paths are added to the autoloader.
1692
        if ($key === 'installed_paths') {
×
1693
            $installedStandards = Standards::getInstalledStandardDetails();
×
1694
            foreach ($installedStandards as $details) {
×
1695
                Autoload::addSearchPath($details['path'], $details['namespace']);
×
1696
            }
1697
        }
1698

1699
        return true;
×
1700

1701
    }//end setConfigData()
1702

1703

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

1717
        $path = '';
×
1718
        if (is_callable('\Phar::running') === true) {
×
1719
            $path = Phar::running(false);
×
1720
        }
1721

1722
        if ($path !== '') {
×
1723
            $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1724
        } else {
1725
            $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1726
            if (is_file($configFile) === false
×
1727
                && strpos('@data_dir@', '@data_dir') === false
×
1728
            ) {
1729
                $configFile = '@data_dir@/PHP_CodeSniffer/CodeSniffer.conf';
×
1730
            }
1731
        }
1732

1733
        if (is_file($configFile) === false) {
×
1734
            self::$configData = [];
×
1735
            return [];
×
1736
        }
1737

1738
        if (Common::isReadable($configFile) === false) {
×
1739
            $error = 'ERROR: Config file '.$configFile.' is not readable'.PHP_EOL.PHP_EOL;
×
1740
            throw new DeepExitException($error, 3);
×
1741
        }
1742

1743
        include $configFile;
×
1744
        self::$configDataFile = $configFile;
×
1745
        self::$configData     = $phpCodeSnifferConfig;
×
1746
        return self::$configData;
×
1747

1748
    }//end getAllConfigData()
1749

1750

1751
    /**
1752
     * Prepares the gathered config data for display.
1753
     *
1754
     * @param array<string, string> $data The config data to format for display.
1755
     *
1756
     * @return string
1757
     */
1758
    public function prepareConfigDataForDisplay($data)
18✔
1759
    {
1760
        if (empty($data) === true) {
18✔
1761
            return '';
6✔
1762
        }
1763

1764
        $max  = 0;
12✔
1765
        $keys = array_keys($data);
12✔
1766
        foreach ($keys as $key) {
12✔
1767
            $len = strlen($key);
12✔
1768
            if ($len > $max) {
12✔
1769
                $max = $len;
12✔
1770
            }
1771
        }
1772

1773
        $max += 2;
12✔
1774
        ksort($data);
12✔
1775

1776
        $output = '';
12✔
1777
        foreach ($data as $name => $value) {
12✔
1778
            $output .= str_pad($name.': ', $max).$value.PHP_EOL;
12✔
1779
        }
1780

1781
        return $output;
12✔
1782

1783
    }//end prepareConfigDataForDisplay()
1784

1785

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

1799
    }//end printConfigData()
1✔
1800

1801

1802
}//end class
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc