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

PHPCSStandards / PHP_CodeSniffer / 15637524486

13 Jun 2025 02:54PM UTC coverage: 78.436% (+0.06%) from 78.375%
15637524486

Pull #1108

github

web-flow
Merge ce5067991 into ef0b6a62c
Pull Request #1108: Squiz/SelfMemberReference: update XML doc

25193 of 32119 relevant lines covered (78.44%)

69.39 hits per line

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

36.37
/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.13.2';
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)
183✔
765
    {
766
        switch ($arg) {
61✔
767
        case 'help':
183✔
768
            ob_start();
×
769
            $this->printUsage();
×
770
            $output = ob_get_contents();
×
771
            ob_end_clean();
×
772
            throw new DeepExitException($output, 0);
×
773
        case 'version':
183✔
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':
183✔
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':
183✔
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':
183✔
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':
183✔
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':
183✔
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':
183✔
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':
183✔
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':
183✔
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':
183✔
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:
61✔
898
            if (substr($arg, 0, 7) === 'sniffs=') {
183✔
899
                if (isset(self::$overriddenDefaults['sniffs']) === true) {
57✔
900
                    break;
3✔
901
                }
902

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1157
                        if (isset($this->extensions[$ext]) === true) {
18✔
1158
                            $newExtensions[$ext] = $this->extensions[$ext];
15✔
1159
                        } else {
5✔
1160
                            $newExtensions[$ext] = 'PHP';
6✔
1161
                        }
1162
                    }
7✔
1163
                }
7✔
1164

1165
                $this->extensions = $newExtensions;
24✔
1166
                self::$overriddenDefaults['extensions'] = true;
24✔
1167
            } else if (substr($arg, 0, 7) === 'suffix=') {
38✔
1168
                if (isset(self::$overriddenDefaults['suffix']) === true) {
×
1169
                    break;
×
1170
                }
1171

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

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

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

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

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

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

1217
                $ignored = [];
×
1218
                foreach ($patterns as $pattern) {
×
1219
                    $pattern = trim($pattern);
×
1220
                    if ($pattern === '') {
×
1221
                        continue;
×
1222
                    }
1223

1224
                    $ignored[$pattern] = 'absolute';
×
1225
                }
1226

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

1236
                $generatorName          = substr($arg, 10);
30✔
1237
                $lowerCaseGeneratorName = strtolower($generatorName);
30✔
1238

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

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

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

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

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

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

1292
    }//end processLongArgument()
68✔
1293

1294

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

1309
        $possibleSniffs = array_filter(explode(',', $input));
114✔
1310

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

1315
        foreach ($possibleSniffs as $sniff) {
114✔
1316
            $sniff = trim($sniff);
96✔
1317

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

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

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

1341
        $sniffs = array_reduce(
114✔
1342
            $sniffs,
114✔
1343
            static function ($carry, $item) {
76✔
1344
                $lower = strtolower($item);
78✔
1345

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

1353
                $carry[] = $item;
78✔
1354

1355
                return $carry;
78✔
1356
            },
114✔
1357
            []
114✔
1358
        );
76✔
1359

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

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

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

1377
        return $sniffs;
42✔
1378

1379
    }//end parseSniffCodes()
1380

1381

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

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

1406
        $this->processFilePath($arg);
×
1407

1408
    }//end processUnknownArgument()
1409

1410

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

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

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

1444
    }//end processFilePath()
1445

1446

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

1456
        if (PHP_CODESNIFFER_CBF === true) {
×
1457
            $this->printPHPCBFUsage();
×
1458
        } else {
1459
            $this->printPHPCSUsage();
×
1460
        }
1461

1462
        echo PHP_EOL;
×
1463

1464
    }//end printUsage()
1465

1466

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

1483
        $usage .= PHP_EOL.PHP_EOL;
×
1484

1485
        if ($return === true) {
×
1486
            return $usage;
×
1487
        }
1488

1489
        echo $usage;
×
1490

1491
    }//end printShortUsage()
1492

1493

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

1513
        $shortOptions = Help::DEFAULT_SHORT_OPTIONS.'aems';
×
1514

1515
        (new Help($this, $longOptions, $shortOptions))->display();
×
1516

1517
    }//end printPHPCSUsage()
1518

1519

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

1531
        (new Help($this, $longOptions, $shortOptions))->display();
×
1532

1533
    }//end printPHPCBFUsage()
1534

1535

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

1549
        if ($phpCodeSnifferConfig === null) {
6✔
1550
            return null;
×
1551
        }
1552

1553
        if (isset($phpCodeSnifferConfig[$key]) === false) {
6✔
1554
            return null;
6✔
1555
        }
1556

1557
        return $phpCodeSnifferConfig[$key];
6✔
1558

1559
    }//end getConfigData()
1560

1561

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

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

1582
        if (array_key_exists($name, self::$executablePaths) === true) {
4✔
1583
            return self::$executablePaths[$name];
2✔
1584
        }
1585

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

1592
        $result = exec($cmd, $output, $retVal);
4✔
1593
        if ($retVal !== 0) {
4✔
1594
            $result = null;
×
1595
        }
1596

1597
        self::$executablePaths[$name] = $result;
4✔
1598
        return $result;
4✔
1599

1600
    }//end getExecutablePath()
1601

1602

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

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

1632
            if ($path !== '') {
×
1633
                $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1634
            } else {
1635
                $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1636
            }
1637

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

1646
        $phpCodeSnifferConfig = self::getAllConfigData();
×
1647

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

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

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

1666
            self::$configDataFile = $configFile;
×
1667
        }
1668

1669
        self::$configData = $phpCodeSnifferConfig;
×
1670

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

1680
        return true;
×
1681

1682
    }//end setConfigData()
1683

1684

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

1698
        $path = '';
×
1699
        if (is_callable('\Phar::running') === true) {
×
1700
            $path = Phar::running(false);
×
1701
        }
1702

1703
        if ($path !== '') {
×
1704
            $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1705
        } else {
1706
            $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1707
        }
1708

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

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

1719
        include $configFile;
×
1720
        self::$configDataFile = $configFile;
×
1721
        self::$configData     = $phpCodeSnifferConfig;
×
1722
        return self::$configData;
×
1723

1724
    }//end getAllConfigData()
1725

1726

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

1745
        if ($max === 0) {
×
1746
            return;
×
1747
        }
1748

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

1755
    }//end printConfigData()
1756

1757

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