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

PHPCSStandards / PHP_CodeSniffer / 14537835549

18 Apr 2025 03:54PM UTC coverage: 78.154%. Remained the same
14537835549

Pull #1035

github

web-flow
Merge 82dd0e14a into 7a3c1e347
Pull Request #1035: Modernize: use `PHP_OS_FAMILY` constant

3 of 7 new or added lines in 5 files covered. (42.86%)

19480 of 24925 relevant lines covered (78.15%)

85.56 hits per line

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

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

13
namespace PHP_CodeSniffer;
14

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

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

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

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

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

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

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

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

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

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

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

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

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

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

236

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

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

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

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

269
    }//end __get()
270

271

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

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

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

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

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

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

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

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

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

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

342
    }//end __set()
16✔
343

344

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

356
    }//end __isset()
357

358

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

370
    }//end __unset()
371

372

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

382
    }//end getSettings()
383

384

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

396
    }//end setSettings()
397

398

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

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

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

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

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

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

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

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

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

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

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

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

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

486
        fclose($handle);
×
487

488
    }//end __construct()
489

490

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

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

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

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

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

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

539
    }//end setCommandLineValues()
540

541

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

665
    }//end restoreDefaults()
3✔
666

667

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

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

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

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

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

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

783
    }//end processShortArgument()
5✔
784

785

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

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

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

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

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

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

859
            $key     = $this->cliArgs[($pos + 1)];
×
860
            $value   = $this->cliArgs[($pos + 2)];
×
861
            $current = self::getConfigData($key);
×
862

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

869
            $output = 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL;
×
870

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

884
            $output = 'Using config file: '.self::$configDataFile.PHP_EOL.PHP_EOL;
×
885

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

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

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

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

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

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

953
                // Turn caching on.
954
                $this->cache = true;
×
955
                $this->overriddenDefaults['cache'] = true;
×
956

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

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

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

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

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

988
                $this->overriddenDefaults['cacheFile'] = true;
×
989

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

1006
                    $bootstrap[] = $path;
×
1007
                }
1008

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

1020
                $files = file($path);
×
1021
                foreach ($files as $inputFile) {
×
1022
                    $inputFile = trim($inputFile);
×
1023

1024
                    // Skip empty lines.
1025
                    if ($inputFile === '') {
×
1026
                        continue;
×
1027
                    }
1028

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

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

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

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

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

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

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

1062
                    $this->reportFile = $dir.'/'.basename($this->reportFile);
×
1063
                }//end if
1064

1065
                $this->overriddenDefaults['reportFile'] = true;
×
1066

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

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

1084
                $this->overriddenDefaults['basepath'] = true;
×
1085

1086
                if (substr($arg, 9) === '') {
×
1087
                    $this->basepath = null;
×
1088
                    break;
×
1089
                }
1090

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

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

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

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

1125
                            $output = $dir.'/'.basename($output);
×
1126

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

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

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

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

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

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

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

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

1192
                        $newExtensions[$ext] = 'PHP';
21✔
1193
                    }
1194
                }
1195

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

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

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

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

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

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

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

1248
                $ignored = [];
×
1249
                foreach ($patterns as $pattern) {
×
1250
                    $pattern = trim($pattern);
×
1251
                    if ($pattern === '') {
×
1252
                        continue;
×
1253
                    }
1254

1255
                    $ignored[$pattern] = 'absolute';
×
1256
                }
1257

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

1267
                $generatorName          = substr($arg, 10);
30✔
1268
                $lowerCaseGeneratorName = strtolower($generatorName);
30✔
1269

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

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

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

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

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

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

1323
    }//end processLongArgument()
31✔
1324

1325

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

1340
        $possibleSniffs = array_filter(explode(',', $input));
114✔
1341

1342
        if ($possibleSniffs === []) {
114✔
1343
            $errors[] = 'No codes specified / empty argument';
18✔
1344
        }
1345

1346
        foreach ($possibleSniffs as $sniff) {
114✔
1347
            $sniff = trim($sniff);
96✔
1348

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

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

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

1372
        $sniffs = array_reduce(
114✔
1373
            $sniffs,
114✔
1374
            static function ($carry, $item) {
76✔
1375
                $lower = strtolower($item);
78✔
1376

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

1384
                $carry[] = $item;
78✔
1385

1386
                return $carry;
78✔
1387
            },
114✔
1388
            []
114✔
1389
        );
76✔
1390

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

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

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

1408
        return $sniffs;
42✔
1409

1410
    }//end parseSniffCodes()
1411

1412

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

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

1437
        $this->processFilePath($arg);
×
1438

1439
    }//end processUnknownArgument()
1440

1441

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

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

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

1475
    }//end processFilePath()
1476

1477

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

1487
        if (PHP_CODESNIFFER_CBF === true) {
×
1488
            $this->printPHPCBFUsage();
×
1489
        } else {
1490
            $this->printPHPCSUsage();
×
1491
        }
1492

1493
        echo PHP_EOL;
×
1494

1495
    }//end printUsage()
1496

1497

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

1514
        $usage .= PHP_EOL.PHP_EOL;
×
1515

1516
        if ($return === true) {
×
1517
            return $usage;
×
1518
        }
1519

1520
        echo $usage;
×
1521

1522
    }//end printShortUsage()
1523

1524

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

1544
        $shortOptions = Help::DEFAULT_SHORT_OPTIONS.'aems';
×
1545

1546
        (new Help($this, $longOptions, $shortOptions))->display();
×
1547

1548
    }//end printPHPCSUsage()
1549

1550

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

1562
        (new Help($this, $longOptions, $shortOptions))->display();
×
1563

1564
    }//end printPHPCBFUsage()
1565

1566

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

1580
        if ($phpCodeSnifferConfig === null) {
6✔
1581
            return null;
×
1582
        }
1583

1584
        if (isset($phpCodeSnifferConfig[$key]) === false) {
6✔
1585
            return null;
6✔
1586
        }
1587

1588
        return $phpCodeSnifferConfig[$key];
6✔
1589

1590
    }//end getConfigData()
1591

1592

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

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

1613
        if (array_key_exists($name, self::$executablePaths) === true) {
×
1614
            return self::$executablePaths[$name];
×
1615
        }
1616

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

1623
        $result = exec($cmd, $output, $retVal);
×
1624
        if ($retVal !== 0) {
×
1625
            $result = null;
×
1626
        }
1627

1628
        self::$executablePaths[$name] = $result;
×
1629
        return $result;
×
1630

1631
    }//end getExecutablePath()
1632

1633

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

1657
        if ($temp === false) {
×
1658
            $path = '';
×
1659
            if (is_callable('\Phar::running') === true) {
×
1660
                $path = Phar::running(false);
×
1661
            }
1662

1663
            if ($path !== '') {
×
1664
                $configFile = dirname($path).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1665
            } else {
1666
                $configFile = dirname(__DIR__).DIRECTORY_SEPARATOR.'CodeSniffer.conf';
×
1667
            }
1668

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

1677
        $phpCodeSnifferConfig = self::getAllConfigData();
×
1678

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

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

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

1697
            self::$configDataFile = $configFile;
×
1698
        }
1699

1700
        self::$configData = $phpCodeSnifferConfig;
×
1701

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

1711
        return true;
×
1712

1713
    }//end setConfigData()
1714

1715

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

1729
        $path = '';
×
1730
        if (is_callable('\Phar::running') === true) {
×
1731
            $path = Phar::running(false);
×
1732
        }
1733

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

1745
        if (is_file($configFile) === false) {
×
1746
            self::$configData = [];
×
1747
            return [];
×
1748
        }
1749

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

1755
        include $configFile;
×
1756
        self::$configDataFile = $configFile;
×
1757
        self::$configData     = $phpCodeSnifferConfig;
×
1758
        return self::$configData;
×
1759

1760
    }//end getAllConfigData()
1761

1762

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

1781
        if ($max === 0) {
×
1782
            return;
×
1783
        }
1784

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

1791
    }//end printConfigData()
1792

1793

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

© 2026 Coveralls, Inc