-
Notifications
You must be signed in to change notification settings - Fork 0
/
CodeSniffer.php
2180 lines (1858 loc) · 72 KB
/
CodeSniffer.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
/**
* PHP_CodeSniffer tokenises PHP code and detects violations of a
* defined set of coding standards.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <[email protected]>
* @author Marc McIntyre <[email protected]>
* @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
spl_autoload_register(array('PHP_CodeSniffer', 'autoload'));
if (class_exists('PHP_CodeSniffer_Exception', true) === false) {
throw new Exception('Class PHP_CodeSniffer_Exception not found');
}
if (class_exists('PHP_CodeSniffer_File', true) === false) {
throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_File not found');
}
if (class_exists('PHP_CodeSniffer_Tokens', true) === false) {
throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_Tokens not found');
}
if (class_exists('PHP_CodeSniffer_CLI', true) === false) {
throw new PHP_CodeSniffer_Exception('Class PHP_CodeSniffer_CLI not found');
}
if (interface_exists('PHP_CodeSniffer_Sniff', true) === false) {
throw new PHP_CodeSniffer_Exception('Interface PHP_CodeSniffer_Sniff not found');
}
/**
* PHP_CodeSniffer tokenises PHP code and detects violations of a
* defined set of coding standards.
*
* Standards are specified by classes that implement the PHP_CodeSniffer_Sniff
* interface. A sniff registers what token types it wishes to listen for, then
* PHP_CodeSniffer encounters that token, the sniff is invoked and passed
* information about where the token was found in the stack, and the token stack
* itself.
*
* Sniff files and their containing class must be prefixed with Sniff, and
* have an extension of .php.
*
* Multiple PHP_CodeSniffer operations can be performed by re-calling the
* process function with different parameters.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <[email protected]>
* @author Marc McIntyre <[email protected]>
* @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600)
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
* @version Release: @package_version@
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class PHP_CodeSniffer
{
/**
* The current version.
*
* @var string
*/
const VERSION = '1.5.1';
/**
* Package stability; either stable or beta.
*
* @var string
*/
const STABILITY = 'stable';
/**
* The file or directory that is currently being processed.
*
* @var string
*/
protected $file = '';
/**
* A cache of different token types, resolved into arrays.
*
* @var array()
* @see standardiseToken()
*/
private static $_resolveTokenCache = array();
/**
* The directories that the processed rulesets are in.
*
* This is declared static because it is also used in the
* autoloader to look for sniffs outside the PHPCS install.
* This way, standards designed to be installed inside PHPCS can
* also be used from outside the PHPCS Standards directory.
*
* @var string
*/
protected static $rulesetDirs = array();
/**
* The CLI object controlling the run.
*
* @var PHP_CodeSniffer_CLI
*/
public $cli = null;
/**
* The Reporting object controlling report generation.
*
* @var PHP_CodeSniffer_Reporting
*/
public $reporting = null;
/**
* An array of sniff objects that are being used to check files.
*
* @var array(PHP_CodeSniffer_Sniff)
*/
protected $listeners = array();
/**
* An array of sniffs that are being used to check files.
*
* @var array(string)
*/
protected $sniffs = array();
/**
* The listeners array, indexed by token type.
*
* @var array
*/
private $_tokenListeners = array();
/**
* 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
*/
protected $ruleset = array();
/**
* An array of patterns to use for skipping files.
*
* @var array
*/
protected $ignorePatterns = array();
/**
* An array of extensions for files we will check.
*
* @var array
*/
public $allowedFileExtensions = array(
'php' => 'PHP',
'inc' => 'PHP',
'js' => 'JS',
'css' => 'CSS',
);
/**
* An array of variable types for param/var we will check.
*
* @var array(string)
*/
public static $allowedTypes = array(
'array',
'boolean',
'float',
'integer',
'mixed',
'object',
'string',
'resource',
'callable',
);
/**
* Constructs a PHP_CodeSniffer object.
*
* @param int $verbosity The verbosity level.
* 1: Print progress information.
* 2: Print tokenizer debug information.
* 3: Print sniff debug information.
* @param int $tabWidth The number of spaces each tab represents.
* If greater than zero, tabs will be replaced
* by spaces before testing each file.
* @param string $encoding The charset of the sniffed files.
* This is important for some reports that output
* with utf-8 encoding as you don't want it double
* encoding messages.
* @param bool $interactive If TRUE, will stop after each file with errors
* and wait for user input.
*
* @see process()
*/
public function __construct(
$verbosity=0,
$tabWidth=0,
$encoding='iso-8859-1',
$interactive=false
) {
if (defined('PHP_CODESNIFFER_VERBOSITY') === false) {
define('PHP_CODESNIFFER_VERBOSITY', $verbosity);
}
if (defined('PHP_CODESNIFFER_TAB_WIDTH') === false) {
define('PHP_CODESNIFFER_TAB_WIDTH', $tabWidth);
}
if (defined('PHP_CODESNIFFER_ENCODING') === false) {
define('PHP_CODESNIFFER_ENCODING', $encoding);
}
if (defined('PHP_CODESNIFFER_INTERACTIVE') === false) {
define('PHP_CODESNIFFER_INTERACTIVE', $interactive);
}
if (defined('PHPCS_DEFAULT_ERROR_SEV') === false) {
define('PHPCS_DEFAULT_ERROR_SEV', 5);
}
if (defined('PHPCS_DEFAULT_WARN_SEV') === false) {
define('PHPCS_DEFAULT_WARN_SEV', 5);
}
// Set default CLI object in case someone is running us
// without using the command line script.
$this->cli = new PHP_CodeSniffer_CLI();
$this->cli->errorSeverity = PHPCS_DEFAULT_ERROR_SEV;
$this->cli->warningSeverity = PHPCS_DEFAULT_WARN_SEV;
$this->cli->dieOnUnknownArg = false;
$this->reporting = new PHP_CodeSniffer_Reporting();
}//end __construct()
/**
* Autoload static method for loading classes and interfaces.
*
* @param string $className The name of the class or interface.
*
* @return void
*/
public static function autoload($className)
{
if (substr($className, 0, 4) === 'PHP_') {
$newClassName = substr($className, 4);
} else {
$newClassName = $className;
}
$path = str_replace(array('_', '\\'), '/', $newClassName).'.php';
if (is_file(dirname(__FILE__).'/'.$path) === true) {
// Check standard file locations based on class name.
include dirname(__FILE__).'/'.$path;
} else if (is_file(dirname(__FILE__).'/CodeSniffer/Standards/'.$path) === true) {
// Check for included sniffs.
include dirname(__FILE__).'/CodeSniffer/Standards/'.$path;
} else {
// Check standard file locations based on the loaded rulesets.
foreach (self::$rulesetDirs as $rulesetDir) {
if (is_file(dirname($rulesetDir).'/'.$path) === true) {
include_once dirname($rulesetDir).'/'.$path;
return;
}
}
// Everything else.
@include $path;
}
}//end autoload()
/**
* Sets an array of file extensions that we will allow checking of.
*
* If the extension is one of the defaults, a specific tokenizer
* will be used. Otherwise, the PHP tokenizer will be used for
* all extensions passed.
*
* @param array $extensions An array of file extensions.
*
* @return void
*/
public function setAllowedFileExtensions(array $extensions)
{
$newExtensions = array();
foreach ($extensions as $ext) {
if (isset($this->allowedFileExtensions[$ext]) === true) {
$newExtensions[$ext] = $this->allowedFileExtensions[$ext];
} else {
$newExtensions[$ext] = 'PHP';
}
}
$this->allowedFileExtensions = $newExtensions;
}//end setAllowedFileExtensions()
/**
* Sets an array of ignore patterns that we use to skip files and folders.
*
* Patterns are not case sensitive.
*
* @param array $patterns An array of ignore patterns. The pattern is the key
* and the value is either "absolute" or "relative",
* depending on how the pattern should be applied to a
* file path.
*
* @return void
*/
public function setIgnorePatterns(array $patterns)
{
$this->ignorePatterns = $patterns;
}//end setIgnorePatterns()
/**
* Gets the array of ignore patterns.
*
* Optionally takes a listener to get ignore patterns specified
* for that sniff only.
*
* @param string $listener The listener to get patterns for. If NULL, all
* patterns are returned.
*
* @return array
*/
public function getIgnorePatterns($listener=null)
{
if ($listener === null) {
return $this->ignorePatterns;
}
if (isset($this->ignorePatterns[$listener]) === true) {
return $this->ignorePatterns[$listener];
}
return array();
}//end getIgnorePatterns()
/**
* Sets the internal CLI object.
*
* @param object $cli The CLI object controlling the run.
*
* @return void
*/
public function setCli($cli)
{
$this->cli = $cli;
}//end setCli()
/**
* Processes the files/directories that PHP_CodeSniffer was constructed with.
*
* @param string|array $files The files and directories to process. For
* directories, each sub directory will also
* be traversed for source files.
* @param string|array $standards The set of code sniffs we are testing
* against.
* @param array $restrictions The sniff codes to restrict the
* violations to.
* @param boolean $local If true, don't recurse into directories.
*
* @return void
* @throws PHP_CodeSniffer_Exception If files or standard are invalid.
*/
public function process($files, $standards, array $restrictions=array(), $local=false)
{
if (is_array($files) === false) {
$files = array($files);
}
if (is_array($standards) === false) {
$standards = array($standards);
}
// Reset the members.
$this->listeners = array();
$this->sniffs = array();
$this->ruleset = array();
$this->_tokenListeners = array();
self::$rulesetDirs = array();
// Ensure this option is enabled or else line endings will not always
// be detected properly for files created on a Mac with the /r line ending.
ini_set('auto_detect_line_endings', true);
$sniffs = array();
foreach ($standards as $standard) {
$installed = $this->getInstalledStandardPath($standard);
if ($installed !== null) {
$standard = $installed;
} else if (is_dir($standard) === true
&& is_file(realpath($standard.'/ruleset.xml')) === true
) {
$standard = realpath($standard.'/ruleset.xml');
}
if (PHP_CODESNIFFER_VERBOSITY === 1) {
$ruleset = simplexml_load_file($standard);
if ($ruleset !== false) {
$standardName = (string) $ruleset['name'];
}
echo "Registering sniffs in the $standardName standard... ";
if (count($standards) > 1 || PHP_CODESNIFFER_VERBOSITY > 2) {
echo PHP_EOL;
}
}
$sniffs = array_merge($sniffs, $this->processRuleset($standard));
}//end foreach
$sniffRestrictions = array();
foreach ($restrictions as $sniffCode) {
$parts = explode('.', strtolower($sniffCode));
$sniffRestrictions[] = $parts[0].'_sniffs_'.$parts[1].'_'.$parts[2].'sniff';
}
$this->registerSniffs($sniffs, $sniffRestrictions);
$this->populateTokenListeners();
if (PHP_CODESNIFFER_VERBOSITY === 1) {
$numSniffs = count($this->sniffs);
echo "DONE ($numSniffs sniffs registered)".PHP_EOL;
}
// The SVN pre-commit calls process() to init the sniffs
// and ruleset so there may not be any files to process.
// But this has to come after that initial setup.
if (empty($files) === true) {
return;
}
$cliValues = $this->cli->getCommandLineValues();
$showProgress = $cliValues['showProgress'];
if (PHP_CODESNIFFER_VERBOSITY > 0) {
echo 'Creating file list... ';
}
$todo = $this->getFilesToProcess($files, $local);
$numFiles = count($todo);
if (PHP_CODESNIFFER_VERBOSITY > 0) {
echo "DONE ($numFiles files in queue)".PHP_EOL;
}
$numProcessed = 0;
$dots = 0;
$maxLength = strlen($numFiles);
$lastDir = '';
foreach ($todo as $file) {
$this->file = $file;
$currDir = dirname($file);
if ($lastDir !== $currDir) {
if (PHP_CODESNIFFER_VERBOSITY > 0) {
echo 'Changing into directory '.$currDir.PHP_EOL;
}
$lastDir = $currDir;
}
$phpcsFile = $this->processFile($file, null, $restrictions);
$numProcessed++;
if (PHP_CODESNIFFER_VERBOSITY > 0
|| PHP_CODESNIFFER_INTERACTIVE === true
|| $showProgress === false
) {
continue;
}
// Show progress information.
if ($phpcsFile === null) {
echo 'S';
} else {
$errors = $phpcsFile->getErrorCount();
$warnings = $phpcsFile->getWarningCount();
if ($errors > 0) {
echo 'E';
} else if ($warnings > 0) {
echo 'W';
} else {
echo '.';
}
}
$dots++;
if ($dots === 60) {
$padding = ($maxLength - strlen($numProcessed));
echo str_repeat(' ', $padding);
$percent = round($numProcessed / $numFiles * 100);
echo " $numProcessed / $numFiles ($percent%)".PHP_EOL;
$dots = 0;
}
}//end foreach
if (PHP_CODESNIFFER_VERBOSITY === 0
&& PHP_CODESNIFFER_INTERACTIVE === false
&& $showProgress === true
) {
echo PHP_EOL.PHP_EOL;
}
}//end process()
/**
* 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 array
* @throws PHP_CodeSniffer_Exception If the ruleset path is invalid.
*/
public function processRuleset($rulesetPath, $depth=0)
{
$rulesetPath = realpath($rulesetPath);
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "Processing ruleset $rulesetPath".PHP_EOL;
}
$ruleset = simplexml_load_file($rulesetPath);
if ($ruleset === false) {
throw new PHP_CodeSniffer_Exception("Ruleset $rulesetPath is not valid");
}
$ownSniffs = array();
$includedSniffs = array();
$excludedSniffs = array();
$rulesetDir = dirname($rulesetPath);
self::$rulesetDirs[] = $rulesetDir;
if (is_dir($rulesetDir.'/Sniffs') === true) {
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\tAdding sniff files from \"/.../".basename($rulesetDir)."/Sniffs/\" directory".PHP_EOL;
}
$ownSniffs = $this->_expandSniffDirectory($rulesetDir.'/Sniffs', $depth);
}
foreach ($ruleset->rule as $rule) {
if (isset($rule['ref']) === false) {
continue;
}
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\tProcessing rule \"".$rule['ref'].'"'.PHP_EOL;
}
$includedSniffs = array_merge(
$includedSniffs,
$this->_expandRulesetReference($rule['ref'], $rulesetDir, $depth)
);
if (isset($rule->exclude) === true) {
foreach ($rule->exclude as $exclude) {
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($exclude['name'], $rulesetDir, ($depth + 1))
);
}
}//end foreach
}//end if
$this->_processRule($rule, $depth);
}//end foreach
// Process custom ignore pattern rules.
foreach ($ruleset->{'config'} as $config) {
$this->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;
}
}
// Process custom ignore pattern rules.
foreach ($ruleset->{'exclude-pattern'} as $pattern) {
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 = array();
foreach ($includedSniffs as $sniff) {
if (in_array($sniff, $excludedSniffs) === true) {
continue;
} else {
$files[] = 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 = array();
if (defined('RecursiveDirectoryIterator::FOLLOW_SYMLINKS') === true) {
$rdi = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::FOLLOW_SYMLINKS);
} else {
$rdi = new RecursiveDirectoryIterator($directory);
}
$di = new RecursiveIteratorIterator($rdi, 0, RecursiveIteratorIterator::CATCH_GET_CHILD);
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();
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> $path".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_Exception 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 array();
}
// 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 = realpath($rulesetDir.'/'.$ref);
if ($realpath !== false) {
$ref = $realpath;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> $ref".PHP_EOL;
}
}
}
if (is_dir($ref) === false && is_file($ref) === false) {
// See if this is a whole standard being referenced.
$path = $this->getInstalledStandardPath($ref);
if ($path !== null) {
$ref = $path;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> $ref".PHP_EOL;
}
} else {
// 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 = '/Sniffs/'.$parts[1];
} else {
// A single sniff?
$path = '/Sniffs/'.$parts[1].'/'.$parts[2].'Sniff.php';
}
}
$newRef = false;
$stdPath = $this->getInstalledStandardPath($stdName);
if ($stdPath !== null && $path !== '') {
$newRef = 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 (self::$rulesetDirs as $dir) {
if (basename($dir) !== $stdName) {
continue;
}
$newRef = realpath($dir.$path);
if ($newRef !== false) {
$ref = $newRef;
}
}
} else {
$ref = $newRef;
}
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> $ref".PHP_EOL;
}
}//end if
}//end if
if (is_dir($ref) === true) {
if (is_file($ref.'/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.'/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 PHP_CodeSniffer_Exception($error);
}
if (substr($ref, -9) === 'Sniff.php') {
// A single sniff.
return array($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 int $depth How many nested processing steps we are in.
* This is only used for debug output.
*
* @return void
*/
private function _processRule($rule, $depth=0)
{
$code = (string) $rule['ref'];
// Custom severity.
if (isset($rule->severity) === true) {
if (isset($this->ruleset[$code]) === false) {
$this->ruleset[$code] = array();
}
$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.PHP_EOL;
}
}
// Custom message type.
if (isset($rule->type) === true) {
if (isset($this->ruleset[$code]) === false) {
$this->ruleset[$code] = array();
}
$this->ruleset[$code]['type'] = (string) $rule->type;
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> message type set to ".(string) $rule->type.PHP_EOL;
}
}
// Custom message.
if (isset($rule->message) === true) {
if (isset($this->ruleset[$code]) === false) {
$this->ruleset[$code] = array();
}
$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.PHP_EOL;
}
}
// Custom properties.
if (isset($rule->properties) === true) {
foreach ($rule->properties->property as $prop) {
if (isset($this->ruleset[$code]) === false) {
$this->ruleset[$code] = array(
'properties' => array(),
);
} else if (isset($this->ruleset[$code]['properties']) === false) {
$this->ruleset[$code]['properties'] = array();
}
$name = (string) $prop['name'];
if (isset($prop['type']) === true
&& (string) $prop['type'] === 'array'
) {
$value = (string) $prop['value'];
$this->ruleset[$code]['properties'][$name] = explode(',', $value);
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> array property \"$name\" set to \"$value\"".PHP_EOL;
}
} else {
$this->ruleset[$code]['properties'][$name] = (string) $prop['value'];
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> property \"$name\" set to \"".(string) $prop['value'].'"'.PHP_EOL;
}
}
}//end foreach
}//end if
// Ignore patterns.
foreach ($rule->{'exclude-pattern'} as $pattern) {
if (isset($this->ignorePatterns[$code]) === false) {
$this->ignorePatterns[$code] = array();
}
if (isset($pattern['type']) === false) {
$pattern['type'] = 'absolute';
}
$this->ignorePatterns[$code][(string) $pattern] = (string) $pattern['type'];
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo str_repeat("\t", $depth);
echo "\t\t=> added sniff-specific ".(string) $pattern['type'].' ignore pattern: '.(string) $pattern.PHP_EOL;
}
}
}//end _processRule()
/**
* Loads and stores sniffs objects used for sniffing files.
*
* @param array $files Paths to the sniff files to register.
* @param array $restrictions The sniff class names to restrict the allowed
* listeners to.
*
* @return void
*/
public function registerSniffs($files, $restrictions)
{
$listeners = array();
foreach ($files as $file) {
// Work out where the position of /StandardName/Sniffs/... is
// so we can determine what the class will be called.
$sniffPos = strrpos($file, DIRECTORY_SEPARATOR.'Sniffs'.DIRECTORY_SEPARATOR);
if ($sniffPos === false) {
continue;
}
$slashPos = strrpos(substr($file, 0, $sniffPos), DIRECTORY_SEPARATOR);
if ($slashPos === false) {
continue;
}
$className = substr($file, ($slashPos + 1));
$className = substr($className, 0, -4);
$className = str_replace(DIRECTORY_SEPARATOR, '_', $className);
// If they have specified a list of sniffs to restrict to, check