-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathRuleset.php
1458 lines (1234 loc) · 52.7 KB
/
Ruleset.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Stores the rules used to check and fix files.
*
* A ruleset object directly maps to a ruleset XML file.
*
* @author Greg Sherwood <gsherwood@squiz.net>
* @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
*/
namespace PHP_CodeSniffer;
use PHP_CodeSniffer\Exceptions\RuntimeException;
use PHP_CodeSniffer\Util;
use stdClass;
class Ruleset
{
/**
* The name of the coding standard being used.
*
* If a top-level standard includes other standards, or sniffs
* from other standards, only the name of the top-level standard
* will be stored in here.
*
* If multiple top-level standards are being loaded into
* a single ruleset object, this will store a comma separated list
* of the top-level standard names.
*
* @var string
*/
public $name = '';
/**
* A list of file paths for the ruleset files being used.
*
* @var string[]
*/
public $paths = [];
/**
* A list of regular expressions used to ignore specific sniffs for files and folders.
*
* Is also used to set global exclude patterns.
* The key is the regular expression and the value is the type
* of ignore pattern (absolute or relative).
*
* @var array<string, string>
*/
public $ignorePatterns = [];
/**
* A list of regular expressions used to include specific sniffs for files and folders.
*
* The key is the sniff code and the value is an array with
* the key being a regular expression and the value is the type
* of ignore pattern (absolute or relative).
*
* @var array<string, array<string, string>>
*/
public $includePatterns = [];
/**
* An array of sniff objects that are being used to check files.
*
* The key is the fully qualified name of the sniff class
* and the value is the sniff object.
*
* @var array<string, \PHP_CodeSniffer\Sniffs\Sniff>
*/
public $sniffs = [];
/**
* A mapping of sniff codes to fully qualified class names.
*
* The key is the sniff code and the value
* is the fully qualified name of the sniff class.
*
* @var array<string, string>
*/
public $sniffCodes = [];
/**
* An array of token types and the sniffs that are listening for them.
*
* The key is the token name being listened for and the value
* is the sniff object.
*
* @var array<int, \PHP_CodeSniffer\Sniffs\Sniff>
*/
public $tokenListeners = [];
/**
* An array of rules from the ruleset.xml file.
*
* It may be empty, indicating that the ruleset does not override
* any of the default sniff settings.
*
* @var array<string, mixed>
*/
public $ruleset = [];
/**
* The directories that the processed rulesets are in.
*
* @var string[]
*/
protected $rulesetDirs = [];
/**
* The config data for the run.
*
* @var \PHP_CodeSniffer\Config
*/
private $config = null;
/**
* Initialise the ruleset that the run will use.
*
* @param \PHP_CodeSniffer\Config $config The config data for the run.
*
* @return void
* @throws \PHP_CodeSniffer\Exceptions\RuntimeException If no sniffs were registered.
*/
public function __construct(Config $config)
{
$this->config = $config;
$restrictions = $config->sniffs;
$exclusions = $config->exclude;
$sniffs = [];
$standardPaths = [];
foreach ($config->standards as $standard) {
$installed = Util\Standards::getInstalledStandardPath($standard);
if ($installed === null) {
$standard = Util\Common::realpath($standard);
if (is_dir($standard) === true
&& is_file(Util\Common::realpath($standard.DIRECTORY_SEPARATOR.'ruleset.xml')) === true
) {
$standard = Util\Common::realpath($standard.DIRECTORY_SEPARATOR.'ruleset.xml');
}
} else {
$standard = $installed;
}
$standardPaths[] = $standard;
}
foreach ($standardPaths as $standard) {
$ruleset = @simplexml_load_string(file_get_contents($standard));
if ($ruleset !== false) {
$standardName = (string) $ruleset['name'];
if ($this->name !== '') {
$this->name .= ', ';
}
$this->name .= $standardName;
// Allow autoloading of custom files inside this standard.
if (isset($ruleset['namespace']) === true) {
$namespace = (string) $ruleset['namespace'];
} else {
$namespace = basename(dirname($standard));
}
Autoload::addSearchPath(dirname($standard), $namespace);
}
if (defined('PHP_CODESNIFFER_IN_TESTS') === true && empty($restrictions) === false) {
// In unit tests, only register the sniffs that the test wants and not the entire standard.
try {
foreach ($restrictions as $restriction) {
$sniffs = array_merge($sniffs, $this->expandRulesetReference($restriction, dirname($standard)));
}
} catch (RuntimeException $e) {
// Sniff reference could not be expanded, which probably means this
// is an installed standard. Let the unit test system take care of
// setting the correct sniff for testing.
return;
}
break;
}
if (PHP_CODESNIFFER_VERBOSITY === 1) {
echo "Registering sniffs in the $standardName standard... ";
if (count($config->standards) > 1 || PHP_CODESNIFFER_VERBOSITY > 2) {
echo PHP_EOL;
}
}
$sniffs = array_merge($sniffs, $this->processRuleset($standard));
}//end foreach
// Ignore sniff restrictions if caching is on.
if ($config->cache === true) {
$restrictions = [];
$exclusions = [];
}
$sniffRestrictions = [];
foreach ($restrictions as $sniffCode) {
$parts = explode('.', strtolower($sniffCode));
$sniffName = $parts[0].'\sniffs\\'.$parts[1].'\\'.$parts[2].'sniff';
$sniffRestrictions[$sniffName] = true;
}
$sniffExclusions = [];
foreach ($exclusions as $sniffCode) {
$parts = explode('.', strtolower($sniffCode));
$sniffName = $parts[0].'\sniffs\\'.$parts[1].'\\'.$parts[2].'sniff';
$sniffExclusions[$sniffName] = true;
}
$this->registerSniffs($sniffs, $sniffRestrictions, $sniffExclusions);
$this->populateTokenListeners();
$numSniffs = count($this->sniffs);
if (PHP_CODESNIFFER_VERBOSITY === 1) {
echo "DONE ($numSniffs sniffs registered)".PHP_EOL;
}
if ($numSniffs === 0) {
throw new RuntimeException('No sniffs were registered');
}
}//end __construct()
/**
* Prints a report showing the sniffs contained in a standard.
*
* @return void
*/
public function explain()
{
$sniffs = array_keys($this->sniffCodes);
sort($sniffs);
ob_start();
$lastStandard = null;
$lastCount = '';
$sniffCount = count($sniffs);
// Add a dummy entry to the end so we loop
// one last time and clear the output buffer.
$sniffs[] = '';
$summaryLine = PHP_EOL."The $this->name standard contains 1 sniff".PHP_EOL;
if ($sniffCount !== 1) {
$summaryLine = str_replace('1 sniff', "$sniffCount sniffs", $summaryLine);
}
echo $summaryLine;
ob_start();
foreach ($sniffs as $i => $sniff) {
if ($i === $sniffCount) {
$currentStandard = null;
} else {
$currentStandard = substr($sniff, 0, strpos($sniff, '.'));
if ($lastStandard === null) {
$lastStandard = $currentStandard;
}
}
if ($currentStandard !== $lastStandard) {
$sniffList = ob_get_contents();
ob_end_clean();
echo PHP_EOL.$lastStandard.' ('.$lastCount.' sniff';
if ($lastCount > 1) {
echo 's';
}
echo ')'.PHP_EOL;
echo str_repeat('-', (strlen($lastStandard.$lastCount) + 10));
echo PHP_EOL;
echo $sniffList;
$lastStandard = $currentStandard;
$lastCount = 0;
if ($currentStandard === null) {
break;
}
ob_start();
}//end if
echo ' '.$sniff.PHP_EOL;
$lastCount++;
}//end foreach
}//end explain()
/**
* Processes a single ruleset and returns a list of the sniffs it represents.
*
* Rules founds within the ruleset are processed immediately, but sniff classes
* are not registered by this method.
*
* @param string $rulesetPath The path to a ruleset XML file.
* @param int $depth How many nested processing steps we are in. This
* is only used for debug output.
*
* @return string[]
* @throws \PHP_CodeSniffer\Exceptions\RuntimeException - If the ruleset path is invalid.
* - If a specified autoload file could not be found.
*/
public function processRuleset($rulesetPath, $depth=0)
{
$rulesetPath = Util\Common::realpath($rulesetPath);
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo 'Processing ruleset '.Util\Common::stripBasepath($rulesetPath, $this->config->basepath).PHP_EOL;
}
libxml_use_internal_errors(true);
$ruleset = simplexml_load_string(file_get_contents($rulesetPath));
if ($ruleset === false) {
$errorMsg = "Ruleset $rulesetPath is not valid".PHP_EOL;
$errors = libxml_get_errors();
foreach ($errors as $error) {
$errorMsg .= '- On line '.$error->line.', column '.$error->column.': '.$error->message;
}
libxml_clear_errors();
throw new RuntimeException($errorMsg);
}
libxml_use_internal_errors(false);
$ownSniffs = [];
$includedSniffs = [];
$excludedSniffs = [];
$this->paths[] = $rulesetPath;
$rulesetDir = dirname($rulesetPath);
$this->rulesetDirs[] = $rulesetDir;
$sniffDir = $rulesetDir.DIRECTORY_SEPARATOR.'Sniffs';
if (is_dir($sniffDir) === true) {
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\tAdding sniff files from ".Util\Common::stripBasepath($sniffDir, $this->config->basepath).' directory'.PHP_EOL;
}
$ownSniffs = $this->expandSniffDirectory($sniffDir, $depth);
}
// Include custom autoloaders.
foreach ($ruleset->{'autoload'} as $autoload) {
if ($this->shouldProcessElement($autoload) === false) {
continue;
}
$autoloadPath = (string) $autoload;
// Try relative autoload paths first.
$relativePath = Util\Common::realPath(dirname($rulesetPath).DIRECTORY_SEPARATOR.$autoloadPath);
if ($relativePath !== false && is_file($relativePath) === true) {
$autoloadPath = $relativePath;
} else if (is_file($autoloadPath) === false) {
throw new RuntimeException('The specified autoload file "'.$autoload.'" does not exist');
}
include_once $autoloadPath;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t=> included autoloader $autoloadPath".PHP_EOL;
}
}//end foreach
// Process custom sniff config settings.
foreach ($ruleset->{'config'} as $config) {
if ($this->shouldProcessElement($config) === false) {
continue;
}
Config::setConfigData((string) $config['name'], (string) $config['value'], true);
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t=> set config value ".(string) $config['name'].': '.(string) $config['value'].PHP_EOL;
}
}
foreach ($ruleset->rule as $rule) {
if (isset($rule['ref']) === false
|| $this->shouldProcessElement($rule) === false
) {
continue;
}
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\tProcessing rule \"".$rule['ref'].'"'.PHP_EOL;
}
$expandedSniffs = $this->expandRulesetReference((string) $rule['ref'], $rulesetDir, $depth);
$newSniffs = array_diff($expandedSniffs, $includedSniffs);
$includedSniffs = array_merge($includedSniffs, $expandedSniffs);
$parts = explode('.', $rule['ref']);
if (count($parts) === 4
&& $parts[0] !== ''
&& $parts[1] !== ''
&& $parts[2] !== ''
) {
$sniffCode = $parts[0].'.'.$parts[1].'.'.$parts[2];
if (isset($this->ruleset[$sniffCode]['severity']) === true
&& $this->ruleset[$sniffCode]['severity'] === 0
) {
// This sniff code has already been turned off, but now
// it is being explicitly included again, so turn it back on.
$this->ruleset[(string) $rule['ref']]['severity'] = 5;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t* disabling sniff exclusion for specific message code *".PHP_EOL;
echo str_repeat("\t", $depth);
echo "\t\t=> severity set to 5".PHP_EOL;
}
} else if (empty($newSniffs) === false) {
$newSniff = $newSniffs[0];
if (in_array($newSniff, $ownSniffs, true) === false) {
// Including a sniff that hasn't been included higher up, but
// only including a single message from it. So turn off all messages in
// the sniff, except this one.
$this->ruleset[$sniffCode]['severity'] = 0;
$this->ruleset[(string) $rule['ref']]['severity'] = 5;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\tExcluding sniff \"".$sniffCode.'" except for "'.$parts[3].'"'.PHP_EOL;
}
}
}//end if
}//end if
if (isset($rule->exclude) === true) {
foreach ($rule->exclude as $exclude) {
if (isset($exclude['name']) === false) {
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t* ignoring empty exclude rule *".PHP_EOL;
echo "\t\t\t=> ".$exclude->asXML().PHP_EOL;
}
continue;
}
if ($this->shouldProcessElement($exclude) === false) {
continue;
}
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\tExcluding rule \"".$exclude['name'].'"'.PHP_EOL;
}
// Check if a single code is being excluded, which is a shortcut
// for setting the severity of the message to 0.
$parts = explode('.', $exclude['name']);
if (count($parts) === 4) {
$this->ruleset[(string) $exclude['name']]['severity'] = 0;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> severity set to 0".PHP_EOL;
}
} else {
$excludedSniffs = array_merge(
$excludedSniffs,
$this->expandRulesetReference((string) $exclude['name'], $rulesetDir, ($depth + 1))
);
}
}//end foreach
}//end if
$this->processRule($rule, $newSniffs, $depth);
}//end foreach
// Process custom command line arguments.
$cliArgs = [];
foreach ($ruleset->{'arg'} as $arg) {
if ($this->shouldProcessElement($arg) === false) {
continue;
}
if (isset($arg['name']) === true) {
$argString = '--'.(string) $arg['name'];
if (isset($arg['value']) === true) {
$argString .= '='.(string) $arg['value'];
}
} else {
$argString = '-'.(string) $arg['value'];
}
$cliArgs[] = $argString;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t=> set command line value $argString".PHP_EOL;
}
}//end foreach
// Set custom php ini values as CLI args.
foreach ($ruleset->{'ini'} as $arg) {
if ($this->shouldProcessElement($arg) === false) {
continue;
}
if (isset($arg['name']) === false) {
continue;
}
$name = (string) $arg['name'];
$argString = $name;
if (isset($arg['value']) === true) {
$value = (string) $arg['value'];
$argString .= "=$value";
} else {
$value = 'true';
}
$cliArgs[] = '-d';
$cliArgs[] = $argString;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t=> set PHP ini value $name to $value".PHP_EOL;
}
}//end foreach
if (empty($this->config->files) === true) {
// Process hard-coded file paths.
foreach ($ruleset->{'file'} as $file) {
$file = (string) $file;
$cliArgs[] = $file;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t=> added \"$file\" to the file list".PHP_EOL;
}
}
}
if (empty($cliArgs) === false) {
// Change the directory so all relative paths are worked
// out based on the location of the ruleset instead of
// the location of the user.
$inPhar = Util\Common::isPharFile($rulesetDir);
if ($inPhar === false) {
$currentDir = getcwd();
chdir($rulesetDir);
}
$this->config->setCommandLineValues($cliArgs);
if ($inPhar === false) {
chdir($currentDir);
}
}
// Process custom ignore pattern rules.
foreach ($ruleset->{'exclude-pattern'} as $pattern) {
if ($this->shouldProcessElement($pattern) === false) {
continue;
}
if (isset($pattern['type']) === false) {
$pattern['type'] = 'absolute';
}
$this->ignorePatterns[(string) $pattern] = (string) $pattern['type'];
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t=> added global ".(string) $pattern['type'].' ignore pattern: '.(string) $pattern.PHP_EOL;
}
}
$includedSniffs = array_unique(array_merge($ownSniffs, $includedSniffs));
$excludedSniffs = array_unique($excludedSniffs);
if (PHP_CODESNIFFER_VERBOSITY > 1) {
$included = count($includedSniffs);
$excluded = count($excludedSniffs);
echo str_repeat("\t", $depth);
echo "=> Ruleset processing complete; included $included sniffs and excluded $excluded".PHP_EOL;
}
// Merge our own sniff list with our externally included
// sniff list, but filter out any excluded sniffs.
$files = [];
foreach ($includedSniffs as $sniff) {
if (in_array($sniff, $excludedSniffs, true) === true) {
continue;
} else {
$files[] = Util\Common::realpath($sniff);
}
}
return $files;
}//end processRuleset()
/**
* Expands a directory into a list of sniff files within.
*
* @param string $directory The path to a directory.
* @param int $depth How many nested processing steps we are in. This
* is only used for debug output.
*
* @return array
*/
private function expandSniffDirectory($directory, $depth=0)
{
$sniffs = [];
$rdi = new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::FOLLOW_SYMLINKS);
$di = new \RecursiveIteratorIterator($rdi, 0, \RecursiveIteratorIterator::CATCH_GET_CHILD);
$dirLen = strlen($directory);
foreach ($di as $file) {
$filename = $file->getFilename();
// Skip hidden files.
if (substr($filename, 0, 1) === '.') {
continue;
}
// We are only interested in PHP and sniff files.
$fileParts = explode('.', $filename);
if (array_pop($fileParts) !== 'php') {
continue;
}
$basename = basename($filename, '.php');
if (substr($basename, -5) !== 'Sniff') {
continue;
}
$path = $file->getPathname();
// Skip files in hidden directories within the Sniffs directory of this
// standard. We use the offset with strpos() to allow hidden directories
// before, valid example:
// /home/foo/.composer/vendor/squiz/custom_tool/MyStandard/Sniffs/...
if (strpos($path, DIRECTORY_SEPARATOR.'.', $dirLen) !== false) {
continue;
}
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> ".Util\Common::stripBasepath($path, $this->config->basepath).PHP_EOL;
}
$sniffs[] = $path;
}//end foreach
return $sniffs;
}//end expandSniffDirectory()
/**
* Expands a ruleset reference into a list of sniff files.
*
* @param string $ref The reference from the ruleset XML file.
* @param string $rulesetDir The directory of the ruleset XML file, used to
* evaluate relative paths.
* @param int $depth How many nested processing steps we are in. This
* is only used for debug output.
*
* @return array
* @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the reference is invalid.
*/
private function expandRulesetReference($ref, $rulesetDir, $depth=0)
{
// Ignore internal sniffs codes as they are used to only
// hide and change internal messages.
if (substr($ref, 0, 9) === 'Internal.') {
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t* ignoring internal sniff code *".PHP_EOL;
}
return [];
}
// As sniffs can't begin with a full stop, assume references in
// this format are relative paths and attempt to convert them
// to absolute paths. If this fails, let the reference run through
// the normal checks and have it fail as normal.
if (substr($ref, 0, 1) === '.') {
$realpath = Util\Common::realpath($rulesetDir.'/'.$ref);
if ($realpath !== false) {
$ref = $realpath;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> ".Util\Common::stripBasepath($ref, $this->config->basepath).PHP_EOL;
}
}
}
// As sniffs can't begin with a tilde, assume references in
// this format are relative to the user's home directory.
if (substr($ref, 0, 2) === '~/') {
$realpath = Util\Common::realpath($ref);
if ($realpath !== false) {
$ref = $realpath;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> ".Util\Common::stripBasepath($ref, $this->config->basepath).PHP_EOL;
}
}
}
if (is_file($ref) === true) {
if (substr($ref, -9) === 'Sniff.php') {
// A single external sniff.
$this->rulesetDirs[] = dirname(dirname(dirname($ref)));
return [$ref];
}
} else {
// See if this is a whole standard being referenced.
$path = Util\Standards::getInstalledStandardPath($ref);
if ($path !== null && Util\Common::isPharFile($path) === true && strpos($path, 'ruleset.xml') === false) {
// If the ruleset exists inside the phar file, use it.
if (file_exists($path.DIRECTORY_SEPARATOR.'ruleset.xml') === true) {
$path .= DIRECTORY_SEPARATOR.'ruleset.xml';
} else {
$path = null;
}
}
if ($path !== null) {
$ref = $path;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> ".Util\Common::stripBasepath($ref, $this->config->basepath).PHP_EOL;
}
} else if (is_dir($ref) === false) {
// Work out the sniff path.
$sepPos = strpos($ref, DIRECTORY_SEPARATOR);
if ($sepPos !== false) {
$stdName = substr($ref, 0, $sepPos);
$path = substr($ref, $sepPos);
} else {
$parts = explode('.', $ref);
$stdName = $parts[0];
if (count($parts) === 1) {
// A whole standard?
$path = '';
} else if (count($parts) === 2) {
// A directory of sniffs?
$path = DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR.$parts[1];
} else {
// A single sniff?
$path = DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR.$parts[1].DIRECTORY_SEPARATOR.$parts[2].'Sniff.php';
}
}
$newRef = false;
$stdPath = Util\Standards::getInstalledStandardPath($stdName);
if ($stdPath !== null && $path !== '') {
if (Util\Common::isPharFile($stdPath) === true
&& strpos($stdPath, 'ruleset.xml') === false
) {
// Phar files can only return the directory,
// since ruleset can be omitted if building one standard.
$newRef = Util\Common::realpath($stdPath.$path);
} else {
$newRef = Util\Common::realpath(dirname($stdPath).$path);
}
}
if ($newRef === false) {
// The sniff is not locally installed, so check if it is being
// referenced as a remote sniff outside the install. We do this
// by looking through all directories where we have found ruleset
// files before, looking for ones for this particular standard,
// and seeing if it is in there.
foreach ($this->rulesetDirs as $dir) {
if (strtolower(basename($dir)) !== strtolower($stdName)) {
continue;
}
$newRef = Util\Common::realpath($dir.$path);
if ($newRef !== false) {
$ref = $newRef;
}
}
} else {
$ref = $newRef;
}
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> ".Util\Common::stripBasepath($ref, $this->config->basepath).PHP_EOL;
}
}//end if
}//end if
if (is_dir($ref) === true) {
if (is_file($ref.DIRECTORY_SEPARATOR.'ruleset.xml') === true) {
// We are referencing an external coding standard.
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t* rule is referencing a standard using directory name; processing *".PHP_EOL;
}
return $this->processRuleset($ref.DIRECTORY_SEPARATOR.'ruleset.xml', ($depth + 2));
} else {
// We are referencing a whole directory of sniffs.
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t* rule is referencing a directory of sniffs *".PHP_EOL;
echo str_repeat("\t", $depth);
echo "\t\tAdding sniff files from directory".PHP_EOL;
}
return $this->expandSniffDirectory($ref, ($depth + 1));
}
} else {
if (is_file($ref) === false) {
$error = "Referenced sniff \"$ref\" does not exist";
throw new RuntimeException($error);
}
if (substr($ref, -9) === 'Sniff.php') {
// A single sniff.
return [$ref];
} else {
// Assume an external ruleset.xml file.
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t* rule is referencing a standard using ruleset path; processing *".PHP_EOL;
}
return $this->processRuleset($ref, ($depth + 2));
}
}//end if
}//end expandRulesetReference()
/**
* Processes a rule from a ruleset XML file, overriding built-in defaults.
*
* @param \SimpleXMLElement $rule The rule object from a ruleset XML file.
* @param string[] $newSniffs An array of sniffs that got included by this rule.
* @param int $depth How many nested processing steps we are in.
* This is only used for debug output.
*
* @return void
* @throws \PHP_CodeSniffer\Exceptions\RuntimeException If rule settings are invalid.
*/
private function processRule($rule, $newSniffs, $depth=0)
{
$ref = (string) $rule['ref'];
$todo = [$ref];
$parts = explode('.', $ref);
$partsCount = count($parts);
if ($partsCount <= 2
|| $partsCount > count(array_filter($parts))
|| in_array($ref, $newSniffs) === true
) {
// We are processing a standard, a category of sniffs or a relative path inclusion.
foreach ($newSniffs as $sniffFile) {
$parts = explode(DIRECTORY_SEPARATOR, $sniffFile);
if (count($parts) === 1 && DIRECTORY_SEPARATOR === '\\') {
// Path using forward slashes while running on Windows.
$parts = explode('/', $sniffFile);
}
$sniffName = array_pop($parts);
$sniffCategory = array_pop($parts);
array_pop($parts);
$sniffStandard = array_pop($parts);
$todo[] = $sniffStandard.'.'.$sniffCategory.'.'.substr($sniffName, 0, -9);
}
}
foreach ($todo as $code) {
// Custom severity.
if (isset($rule->severity) === true
&& $this->shouldProcessElement($rule->severity) === true
) {
if (isset($this->ruleset[$code]) === false) {
$this->ruleset[$code] = [];
}
$this->ruleset[$code]['severity'] = (int) $rule->severity;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> severity set to ".(int) $rule->severity;
if ($code !== $ref) {
echo " for $code";
}
echo PHP_EOL;
}
}
// Custom message type.
if (isset($rule->type) === true
&& $this->shouldProcessElement($rule->type) === true
) {
if (isset($this->ruleset[$code]) === false) {
$this->ruleset[$code] = [];
}
$type = strtolower((string) $rule->type);
if ($type !== 'error' && $type !== 'warning') {
throw new RuntimeException("Message type \"$type\" is invalid; must be \"error\" or \"warning\"");
}
$this->ruleset[$code]['type'] = $type;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> message type set to ".(string) $rule->type;
if ($code !== $ref) {
echo " for $code";
}
echo PHP_EOL;
}
}//end if
// Custom message.
if (isset($rule->message) === true
&& $this->shouldProcessElement($rule->message) === true
) {
if (isset($this->ruleset[$code]) === false) {
$this->ruleset[$code] = [];
}
$this->ruleset[$code]['message'] = (string) $rule->message;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> message set to ".(string) $rule->message;
if ($code !== $ref) {
echo " for $code";
}
echo PHP_EOL;
}
}
// Custom properties.
if (isset($rule->properties) === true
&& $this->shouldProcessElement($rule->properties) === true
) {
$propertyScope = 'standard';
if ($code === $ref || substr($ref, -9) === 'Sniff.php') {
$propertyScope = 'sniff';
}
foreach ($rule->properties->property as $prop) {
if ($this->shouldProcessElement($prop) === false) {
continue;
}
if (isset($this->ruleset[$code]) === false) {
$this->ruleset[$code] = [
'properties' => [],
];
} else if (isset($this->ruleset[$code]['properties']) === false) {
$this->ruleset[$code]['properties'] = [];
}
$name = (string) $prop['name'];
if (isset($prop['type']) === true
&& (string) $prop['type'] === 'array'
) {
$values = [];
if (isset($prop['extend']) === true
&& (string) $prop['extend'] === 'true'
&& isset($this->ruleset[$code]['properties'][$name]['value']) === true
) {
$values = $this->ruleset[$code]['properties'][$name]['value'];
}
if (isset($prop->element) === true) {
$printValue = '';
foreach ($prop->element as $element) {
if ($this->shouldProcessElement($element) === false) {
continue;
}