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

PHPCSStandards / PHP_CodeSniffer / 12422945689

20 Dec 2024 12:11AM UTC coverage: 78.284% (+0.009%) from 78.275%
12422945689

Pull #771

github

web-flow
Merge 541e2efb0 into 12c260f0f
Pull Request #771: Config: display user-friendly message when invalid generator is passed

5 of 12 new or added lines in 1 file covered. (41.67%)

70 existing lines in 1 file now uncovered.

24466 of 31253 relevant lines covered (78.28%)

65.86 hits per line

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

28.93
/src/Config.php
1
<?php
2
/**
3
 * Stores the configuration used to run PHPCS and PHPCBF.
4
 *
5
 * Parses the command line to determine user supplied values
6
 * and provides functions to access data stored in config files.
7
 *
8
 * @author    Greg Sherwood <gsherwood@squiz.net>
9
 * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
10
 * @license   https://github.com/PHPCSStandards/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
11
 */
12

13
namespace PHP_CodeSniffer;
14

15
use Exception;
16
use Phar;
17
use PHP_CodeSniffer\Exceptions\DeepExitException;
18
use PHP_CodeSniffer\Exceptions\RuntimeException;
19
use PHP_CodeSniffer\Util\Common;
20
use PHP_CodeSniffer\Util\Help;
21
use PHP_CodeSniffer\Util\Standards;
22

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

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

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

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

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

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

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

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

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

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

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

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

216

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

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

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

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

249
    }//end __get()
250

251

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

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

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

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

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

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

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

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

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

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

322
    }//end __set()
32✔
323

324

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

336
    }//end __isset()
337

338

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

350
    }//end __unset()
351

352

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

362
    }//end getSettings()
363

364

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

376
    }//end setSettings()
377

378

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

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

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

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

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

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

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

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

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

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

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

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

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

466
        fclose($handle);
×
467

468
    }//end __construct()
469

470

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

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

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

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

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

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

519
    }//end setCommandLineValues()
520

521

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

647
    }//end restoreDefaults()
6✔
648

649

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

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

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

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

752
    }//end processShortArgument()
753

754

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

903
                $sniffs = explode(',', substr($arg, 7));
27✔
904
                foreach ($sniffs as $sniff) {
27✔
905
                    if (substr_count($sniff, '.') !== 2) {
27✔
906
                        $error  = 'ERROR: The specified sniff code "'.$sniff.'" is invalid'.PHP_EOL.PHP_EOL;
18✔
907
                        $error .= $this->printShortUsage(true);
18✔
908
                        throw new DeepExitException($error, 3);
18✔
909
                    }
910
                }
4✔
911

912
                $this->sniffs = $sniffs;
9✔
913
                self::$overriddenDefaults['sniffs'] = true;
9✔
914
            } else if (substr($arg, 0, 8) === 'exclude=') {
69✔
915
                if (isset(self::$overriddenDefaults['exclude']) === true) {
27✔
916
                    break;
3✔
917
                }
918

919
                $sniffs = explode(',', substr($arg, 8));
27✔
920
                foreach ($sniffs as $sniff) {
27✔
921
                    if (substr_count($sniff, '.') !== 2) {
27✔
922
                        $error  = 'ERROR: The specified sniff code "'.$sniff.'" is invalid'.PHP_EOL.PHP_EOL;
18✔
923
                        $error .= $this->printShortUsage(true);
18✔
924
                        throw new DeepExitException($error, 3);
18✔
925
                    }
926
                }
4✔
927

928
                $this->exclude = $sniffs;
9✔
929
                self::$overriddenDefaults['exclude'] = true;
9✔
930
            } else if (defined('PHP_CODESNIFFER_IN_TESTS') === false
42✔
931
                && substr($arg, 0, 6) === 'cache='
39✔
932
            ) {
13✔
933
                if ((isset(self::$overriddenDefaults['cache']) === true
×
934
                    && $this->cache === false)
×
935
                    || isset(self::$overriddenDefaults['cacheFile']) === true
×
936
                ) {
937
                    break;
×
938
                }
939

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

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

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

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

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

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

975
                self::$overriddenDefaults['cacheFile'] = true;
×
976

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

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

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

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

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

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

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

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

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

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

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

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

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

1052
                self::$overriddenDefaults['reportFile'] = true;
×
1053

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

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

1071
                self::$overriddenDefaults['basepath'] = true;
×
1072

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

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

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

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

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

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

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

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

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

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

1142
                self::$overriddenDefaults['reports'] = true;
×
1143
            } else if (substr($arg, 0, 7) === 'filter=') {
30✔
1144
                if (isset(self::$overriddenDefaults['filter']) === true) {
×
1145
                    break;
×
1146
                }
1147

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

1156
                self::$overriddenDefaults['standards'] = true;
×
1157
            } else if (substr($arg, 0, 11) === 'extensions=') {
30✔
1158
                if (isset(self::$overriddenDefaults['extensions']) === true) {
×
1159
                    break;
×
1160
                }
1161

1162
                $extensions    = explode(',', substr($arg, 11));
×
1163
                $newExtensions = [];
×
1164
                foreach ($extensions as $ext) {
×
1165
                    $slash = strpos($ext, '/');
×
1166
                    if ($slash !== false) {
×
1167
                        // They specified the tokenizer too.
1168
                        list($ext, $tokenizer) = explode('/', $ext);
×
1169
                        $newExtensions[$ext]   = strtoupper($tokenizer);
×
1170
                        continue;
×
1171
                    }
1172

1173
                    if (isset($this->extensions[$ext]) === true) {
×
1174
                        $newExtensions[$ext] = $this->extensions[$ext];
×
1175
                    } else {
1176
                        $newExtensions[$ext] = 'PHP';
×
1177
                    }
1178
                }
1179

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

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

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

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

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

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

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

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

NEW
1239
                    $ignored[$pattern] = 'absolute';
×
1240
                }
1241

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

1251
                $generatorName          = substr($arg, 10);
30✔
1252
                $lowerCaseGeneratorName = strtolower($generatorName);
30✔
1253

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

1267
                $this->generator = $this->validGenerators[$lowerCaseGeneratorName];
21✔
1268
                self::$overriddenDefaults['generator'] = true;
21✔
1269
            } else if (substr($arg, 0, 9) === 'encoding=') {
7✔
1270
                if (isset(self::$overriddenDefaults['encoding']) === true) {
×
UNCOV
1271
                    break;
×
1272
                }
1273

1274
                $this->encoding = strtolower(substr($arg, 9));
×
1275
                self::$overriddenDefaults['encoding'] = true;
×
1276
            } else if (substr($arg, 0, 10) === 'tab-width=') {
×
1277
                if (isset(self::$overriddenDefaults['tabWidth']) === true) {
×
UNCOV
1278
                    break;
×
1279
                }
1280

1281
                $this->tabWidth = (int) substr($arg, 10);
×
UNCOV
1282
                self::$overriddenDefaults['tabWidth'] = true;
×
1283
            } else {
1284
                if ($this->dieOnUnknownArg === false) {
×
UNCOV
1285
                    $eqPos = strpos($arg, '=');
×
1286
                    try {
UNCOV
1287
                        $unknown = $this->unknown;
×
1288

1289
                        if ($eqPos === false) {
×
UNCOV
1290
                            $unknown[$arg] = $arg;
×
1291
                        } else {
1292
                            $value         = substr($arg, ($eqPos + 1));
×
1293
                            $arg           = substr($arg, 0, $eqPos);
×
UNCOV
1294
                            $unknown[$arg] = $value;
×
1295
                        }
1296

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

1308
    }//end processLongArgument()
32✔
1309

1310

1311
    /**
1312
     * Processes an unknown command line argument.
1313
     *
1314
     * Assumes all unknown arguments are files and folders to check.
1315
     *
1316
     * @param string $arg The command line argument.
1317
     * @param int    $pos The position of the argument on the command line.
1318
     *
1319
     * @return void
1320
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
1321
     */
UNCOV
1322
    public function processUnknownArgument($arg, $pos)
×
1323
    {
1324
        // We don't know about any additional switches; just files.
1325
        if ($arg[0] === '-') {
×
1326
            if ($this->dieOnUnknownArg === false) {
×
UNCOV
1327
                return;
×
1328
            }
1329

1330
            $error  = "ERROR: option \"$arg\" not known".PHP_EOL.PHP_EOL;
×
1331
            $error .= $this->printShortUsage(true);
×
UNCOV
1332
            throw new DeepExitException($error, 3);
×
1333
        }
1334

UNCOV
1335
        $this->processFilePath($arg);
×
1336

1337
    }//end processUnknownArgument()
1338

1339

1340
    /**
1341
     * Processes a file path and add it to the file list.
1342
     *
1343
     * @param string $path The path to the file to add.
1344
     *
1345
     * @return void
1346
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException
1347
     */
UNCOV
1348
    public function processFilePath($path)
×
1349
    {
1350
        // If we are processing STDIN, don't record any files to check.
1351
        if ($this->stdin === true) {
×
UNCOV
1352
            return;
×
1353
        }
1354

1355
        $file = Common::realpath($path);
×
1356
        if (file_exists($file) === false) {
×
1357
            if ($this->dieOnUnknownArg === false) {
×
UNCOV
1358
                return;
×
1359
            }
1360

1361
            $error  = 'ERROR: The file "'.$path.'" does not exist.'.PHP_EOL.PHP_EOL;
×
1362
            $error .= $this->printShortUsage(true);
×
UNCOV
1363
            throw new DeepExitException($error, 3);
×
1364
        } else {
1365
            // Can't modify the files array directly because it's not a real
1366
            // class member, so need to use this little get/modify/set trick.
1367
            $files       = $this->files;
×
1368
            $files[]     = $file;
×
1369
            $this->files = $files;
×
UNCOV
1370
            self::$overriddenDefaults['files'] = true;
×
1371
        }
1372

1373
    }//end processFilePath()
1374

1375

1376
    /**
1377
     * Prints out the usage information for this script.
1378
     *
1379
     * @return void
1380
     */
UNCOV
1381
    public function printUsage()
×
1382
    {
UNCOV
1383
        echo PHP_EOL;
×
1384

1385
        if (PHP_CODESNIFFER_CBF === true) {
×
UNCOV
1386
            $this->printPHPCBFUsage();
×
1387
        } else {
UNCOV
1388
            $this->printPHPCSUsage();
×
1389
        }
1390

UNCOV
1391
        echo PHP_EOL;
×
1392

1393
    }//end printUsage()
1394

1395

1396
    /**
1397
     * Prints out the short usage information for this script.
1398
     *
1399
     * @param bool $return If TRUE, the usage string is returned
1400
     *                     instead of output to screen.
1401
     *
1402
     * @return string|void
1403
     */
UNCOV
1404
    public function printShortUsage($return=false)
×
1405
    {
1406
        if (PHP_CODESNIFFER_CBF === true) {
×
UNCOV
1407
            $usage = 'Run "phpcbf --help" for usage information';
×
1408
        } else {
UNCOV
1409
            $usage = 'Run "phpcs --help" for usage information';
×
1410
        }
1411

UNCOV
1412
        $usage .= PHP_EOL.PHP_EOL;
×
1413

1414
        if ($return === true) {
×
UNCOV
1415
            return $usage;
×
1416
        }
1417

UNCOV
1418
        echo $usage;
×
1419

1420
    }//end printShortUsage()
1421

1422

1423
    /**
1424
     * Prints out the usage information for PHPCS.
1425
     *
1426
     * @return void
1427
     */
UNCOV
1428
    public function printPHPCSUsage()
×
1429
    {
1430
        $longOptions   = explode(',', Help::DEFAULT_LONG_OPTIONS);
×
1431
        $longOptions[] = 'cache';
×
1432
        $longOptions[] = 'no-cache';
×
1433
        $longOptions[] = 'report';
×
1434
        $longOptions[] = 'report-file';
×
1435
        $longOptions[] = 'report-report';
×
1436
        $longOptions[] = 'config-explain';
×
1437
        $longOptions[] = 'config-set';
×
1438
        $longOptions[] = 'config-delete';
×
1439
        $longOptions[] = 'config-show';
×
UNCOV
1440
        $longOptions[] = 'generator';
×
1441

UNCOV
1442
        $shortOptions = Help::DEFAULT_SHORT_OPTIONS.'aems';
×
1443

UNCOV
1444
        (new Help($this, $longOptions, $shortOptions))->display();
×
1445

1446
    }//end printPHPCSUsage()
1447

1448

1449
    /**
1450
     * Prints out the usage information for PHPCBF.
1451
     *
1452
     * @return void
1453
     */
UNCOV
1454
    public function printPHPCBFUsage()
×
1455
    {
1456
        $longOptions   = explode(',', Help::DEFAULT_LONG_OPTIONS);
×
1457
        $longOptions[] = 'suffix';
×
UNCOV
1458
        $shortOptions  = Help::DEFAULT_SHORT_OPTIONS;
×
1459

UNCOV
1460
        (new Help($this, $longOptions, $shortOptions))->display();
×
1461

1462
    }//end printPHPCBFUsage()
1463

1464

1465
    /**
1466
     * Get a single config value.
1467
     *
1468
     * @param string $key The name of the config value.
1469
     *
1470
     * @return string|null
1471
     * @see    setConfigData()
1472
     * @see    getAllConfigData()
1473
     */
1474
    public static function getConfigData($key)
6✔
1475
    {
1476
        $phpCodeSnifferConfig = self::getAllConfigData();
6✔
1477

1478
        if ($phpCodeSnifferConfig === null) {
6✔
UNCOV
1479
            return null;
×
1480
        }
1481

1482
        if (isset($phpCodeSnifferConfig[$key]) === false) {
6✔
1483
            return null;
6✔
1484
        }
1485

1486
        return $phpCodeSnifferConfig[$key];
6✔
1487

1488
    }//end getConfigData()
1489

1490

1491
    /**
1492
     * Get the path to an executable utility.
1493
     *
1494
     * @param string $name The name of the executable utility.
1495
     *
1496
     * @return string|null
1497
     * @see    getConfigData()
1498
     */
1499
    public static function getExecutablePath($name)
4✔
1500
    {
1501
        $data = self::getConfigData($name.'_path');
4✔
1502
        if ($data !== null) {
4✔
UNCOV
1503
            return $data;
×
1504
        }
1505

1506
        if ($name === "php") {
4✔
1507
            // For php, we know the executable path. There's no need to look it up.
UNCOV
1508
            return PHP_BINARY;
×
1509
        }
1510

1511
        if (array_key_exists($name, self::$executablePaths) === true) {
4✔
1512
            return self::$executablePaths[$name];
2✔
1513
        }
1514

1515
        if (stripos(PHP_OS, 'WIN') === 0) {
4✔
1516
            $cmd = 'where '.escapeshellarg($name).' 2> nul';
2✔
1517
        } else {
1✔
1518
            $cmd = 'which '.escapeshellarg($name).' 2> /dev/null';
2✔
1519
        }
1520

1521
        $result = exec($cmd, $output, $retVal);
4✔
1522
        if ($retVal !== 0) {
4✔
UNCOV
1523
            $result = null;
×
1524
        }
1525

1526
        self::$executablePaths[$name] = $result;
4✔
1527
        return $result;
4✔
1528

1529
    }//end getExecutablePath()
1530

1531

1532
    /**
1533
     * Set a single config value.
1534
     *
1535
     * @param string      $key   The name of the config value.
1536
     * @param string|null $value The value to set. If null, the config
1537
     *                           entry is deleted, reverting it to the
1538
     *                           default value.
1539
     * @param boolean     $temp  Set this config data temporarily for this
1540
     *                           script run. This will not write the config
1541
     *                           data to the config file.
1542
     *
1543
     * @return bool
1544
     * @see    getConfigData()
1545
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the config file can not be written.
1546
     */
UNCOV
1547
    public static function setConfigData($key, $value, $temp=false)
×
1548
    {
1549
        if (isset(self::$overriddenDefaults['runtime-set']) === true
×
UNCOV
1550
            && isset(self::$overriddenDefaults['runtime-set'][$key]) === true
×
1551
        ) {
UNCOV
1552
            return false;
×
1553
        }
1554

1555
        if ($temp === false) {
×
1556
            $path = '';
×
1557
            if (is_callable('\Phar::running') === true) {
×
UNCOV
1558
                $path = Phar::running(false);
×
1559
            }
1560

1561
            if ($path !== '') {
×
UNCOV
1562
                $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1563
            } else {
UNCOV
1564
                $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1565
            }
1566

1567
            if (is_file($configFile) === true
×
UNCOV
1568
                && is_writable($configFile) === false
×
1569
            ) {
1570
                $error = 'ERROR: Config file '.$configFile.' is not writable'.PHP_EOL.PHP_EOL;
×
UNCOV
1571
                throw new DeepExitException($error, 3);
×
1572
            }
1573
        }//end if
1574

UNCOV
1575
        $phpCodeSnifferConfig = self::getAllConfigData();
×
1576

1577
        if ($value === null) {
×
1578
            if (isset($phpCodeSnifferConfig[$key]) === true) {
×
UNCOV
1579
                unset($phpCodeSnifferConfig[$key]);
×
1580
            }
1581
        } else {
UNCOV
1582
            $phpCodeSnifferConfig[$key] = $value;
×
1583
        }
1584

1585
        if ($temp === false) {
×
1586
            $output  = '<'.'?php'."\n".' $phpCodeSnifferConfig = ';
×
1587
            $output .= var_export($phpCodeSnifferConfig, true);
×
UNCOV
1588
            $output .= ";\n?".'>';
×
1589

1590
            if (file_put_contents($configFile, $output) === false) {
×
1591
                $error = 'ERROR: Config file '.$configFile.' could not be written'.PHP_EOL.PHP_EOL;
×
UNCOV
1592
                throw new DeepExitException($error, 3);
×
1593
            }
1594

UNCOV
1595
            self::$configDataFile = $configFile;
×
1596
        }
1597

UNCOV
1598
        self::$configData = $phpCodeSnifferConfig;
×
1599

1600
        // If the installed paths are being set, make sure all known
1601
        // standards paths are added to the autoloader.
1602
        if ($key === 'installed_paths') {
×
1603
            $installedStandards = Standards::getInstalledStandardDetails();
×
1604
            foreach ($installedStandards as $details) {
×
UNCOV
1605
                Autoload::addSearchPath($details['path'], $details['namespace']);
×
1606
            }
1607
        }
1608

UNCOV
1609
        return true;
×
1610

1611
    }//end setConfigData()
1612

1613

1614
    /**
1615
     * Get all config data.
1616
     *
1617
     * @return array<string, string>
1618
     * @see    getConfigData()
1619
     * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the config file could not be read.
1620
     */
UNCOV
1621
    public static function getAllConfigData()
×
1622
    {
1623
        if (self::$configData !== null) {
×
UNCOV
1624
            return self::$configData;
×
1625
        }
1626

1627
        $path = '';
×
1628
        if (is_callable('\Phar::running') === true) {
×
UNCOV
1629
            $path = Phar::running(false);
×
1630
        }
1631

1632
        if ($path !== '') {
×
UNCOV
1633
            $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1634
        } else {
1635
            $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1636
            if (is_file($configFile) === false
×
UNCOV
1637
                && strpos('@data_dir@', '@data_dir') === false
×
1638
            ) {
UNCOV
1639
                $configFile = '@data_dir@/PHP_CodeSniffer/CodeSniffer.conf';
×
1640
            }
1641
        }
1642

1643
        if (is_file($configFile) === false) {
×
1644
            self::$configData = [];
×
UNCOV
1645
            return [];
×
1646
        }
1647

1648
        if (Common::isReadable($configFile) === false) {
×
1649
            $error = 'ERROR: Config file '.$configFile.' is not readable'.PHP_EOL.PHP_EOL;
×
UNCOV
1650
            throw new DeepExitException($error, 3);
×
1651
        }
1652

1653
        include $configFile;
×
1654
        self::$configDataFile = $configFile;
×
1655
        self::$configData     = $phpCodeSnifferConfig;
×
UNCOV
1656
        return self::$configData;
×
1657

1658
    }//end getAllConfigData()
1659

1660

1661
    /**
1662
     * Prints out the gathered config data.
1663
     *
1664
     * @param array $data The config data to print.
1665
     *
1666
     * @return void
1667
     */
UNCOV
1668
    public function printConfigData($data)
×
1669
    {
1670
        $max  = 0;
×
1671
        $keys = array_keys($data);
×
1672
        foreach ($keys as $key) {
×
1673
            $len = strlen($key);
×
1674
            if (strlen($key) > $max) {
×
UNCOV
1675
                $max = $len;
×
1676
            }
1677
        }
1678

1679
        if ($max === 0) {
×
UNCOV
1680
            return;
×
1681
        }
1682

1683
        $max += 2;
×
1684
        ksort($data);
×
1685
        foreach ($data as $name => $value) {
×
UNCOV
1686
            echo str_pad($name.': ', $max).$value.PHP_EOL;
×
1687
        }
1688

1689
    }//end printConfigData()
1690

1691

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