forked from squizlabs/PHP_CodeSniffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
File.php
2935 lines (2536 loc) · 106 KB
/
File.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
/**
* A PHP_CodeSniffer_File object represents a PHP source file and the tokens
* associated with it.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <[email protected]>
* @author Marc McIntyre <[email protected]>
* @copyright 2006-2014 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
*/
/**
* A PHP_CodeSniffer_File object represents a PHP source file and the tokens
* associated with it.
*
* It provides a means for traversing the token stack, along with
* other token related operations. If a PHP_CodeSniffer_Sniff finds and error or
* warning within a PHP_CodeSniffer_File, you can raise an error using the
* addError() or addWarning() methods.
*
* <b>Token Information</b>
*
* Each token within the stack contains information about itself:
*
* <code>
* array(
* 'code' => 301, // the token type code (see token_get_all())
* 'content' => 'if', // the token content
* 'type' => 'T_IF', // the token name
* 'line' => 56, // the line number when the token is located
* 'column' => 12, // the column in the line where this token
* // starts (starts from 1)
* 'level' => 2 // the depth a token is within the scopes open
* 'conditions' => array( // a list of scope condition token
* // positions => codes that
* 2 => 50, // openened the scopes that this token exists
* 9 => 353, // in (see conditional tokens section below)
* ),
* );
* </code>
*
* <b>Conditional Tokens</b>
*
* In addition to the standard token fields, conditions contain information to
* determine where their scope begins and ends:
*
* <code>
* array(
* 'scope_condition' => 38, // the token position of the condition
* 'scope_opener' => 41, // the token position that started the scope
* 'scope_closer' => 70, // the token position that ended the scope
* );
* </code>
*
* The condition, the scope opener and the scope closer each contain this
* information.
*
* <b>Parenthesis Tokens</b>
*
* Each parenthesis token (T_OPEN_PARENTHESIS and T_CLOSE_PARENTHESIS) has a
* reference to their opening and closing parenthesis, one being itself, the
* other being its opposite.
*
* <code>
* array(
* 'parenthesis_opener' => 34,
* 'parenthesis_closer' => 40,
* );
* </code>
*
* Some tokens can "own" a set of parenthesis. For example a T_FUNCTION token
* has parenthesis around its argument list. These tokens also have the
* parenthesis_opener and and parenthesis_closer indices. Not all parenthesis
* have owners, for example parenthesis used for arithmetic operations and
* function calls. The parenthesis tokens that have an owner have the following
* auxiliary array indices.
*
* <code>
* array(
* 'parenthesis_opener' => 34,
* 'parenthesis_closer' => 40,
* 'parenthesis_owner' => 33,
* );
* </code>
*
* Each token within a set of parenthesis also has an array indice
* 'nested_parenthesis' which is an array of the
* left parenthesis => right parenthesis token positions.
*
* <code>
* 'nested_parenthesis' => array(
* 12 => 15
* 11 => 14
* );
* </code>
*
* <b>Extended Tokens</b>
*
* PHP_CodeSniffer extends and augments some of the tokens created by
* <i>token_get_all()</i>. A full list of these tokens can be seen in the
* <i>Tokens.php</i> file.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Greg Sherwood <[email protected]>
* @author Marc McIntyre <[email protected]>
* @copyright 2006-2014 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_File
{
/**
* The absolute path to the file associated with this object.
*
* @var string
*/
private $_file = '';
/**
* The EOL character this file uses.
*
* @var string
*/
public $eolChar = '';
/**
* The PHP_CodeSniffer object controlling this run.
*
* @var PHP_CodeSniffer
*/
public $phpcs = null;
/**
* The tokenizer being used for this file.
*
* @var object
*/
public $tokenizer = null;
/**
* The tokenizer being used for this file.
*
* @var string
*/
public $tokenizerType = 'PHP';
/**
* The number of tokens in this file.
*
* Stored here to save calling count() everywhere.
*
* @var int
*/
public $numTokens = 0;
/**
* The tokens stack map.
*
* Note that the tokens in this array differ in format to the tokens
* produced by token_get_all(). Tokens are initially produced with
* token_get_all(), then augmented so that it's easier to process them.
*
* @var array()
* @see Tokens.php
*/
private $_tokens = array();
/**
* The errors raised from PHP_CodeSniffer_Sniffs.
*
* @var array()
* @see getErrors()
*/
private $_errors = array();
/**
* The warnings raised form PHP_CodeSniffer_Sniffs.
*
* @var array()
* @see getWarnings()
*/
private $_warnings = array();
/**
* Record the errors and warnings raised.
*
* @var bool
*/
private $_recordErrors = true;
/**
* And array of lines being ignored by PHP_CodeSniffer.
*
* @var array()
*/
private $_ignoredLines = array();
/**
* The total number of errors raised.
*
* @var int
*/
private $_errorCount = 0;
/**
* The total number of warnings raised.
*
* @var int
*/
private $_warningCount = 0;
/**
* An array of sniffs listening to this file's processing.
*
* @var array(PHP_CodeSniffer_Sniff)
*/
private $_listeners = array();
/**
* The class name of the sniff currently processing the file.
*
* @var string
*/
private $_activeListener = '';
/**
* An array of sniffs being processed and how long they took.
*
* @var array()
*/
private $_listenerTimes = array();
/**
* An array of extensions mapping to the tokenizer to use.
*
* This value gets set by PHP_CodeSniffer when the object is created.
*
* @var array
*/
protected $tokenizers = array();
/**
* An array of rules from the ruleset.xml file.
*
* This value gets set by PHP_CodeSniffer when the object is created.
* 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 sniff codes to restrict violations to.
*
* This value gets set by PHP_CodeSniffer when the object is created.
* It may be empty, indicating that no fitering should take place.
*
* @var array
*/
protected $restrictions = array();
/**
* Constructs a PHP_CodeSniffer_File.
*
* @param string $file The absolute path to the file to process.
* @param array(string) $listeners The initial listeners listening
* to processing of this file.
* @param array $tokenizers An array of extensions mapping
* to the tokenizer to use.
* @param array $ruleset An array of rules from the
* ruleset.xml file.
* @param array $restrictions An array of sniff codes to
* restrict violations to.
* @param PHP_CodeSniffer $phpcs The PHP_CodeSniffer object controlling
* this run.
*
* @throws PHP_CodeSniffer_Exception If the register() method does
* not return an array.
*/
public function __construct(
$file,
array $listeners,
array $tokenizers,
array $ruleset,
array $restrictions,
PHP_CodeSniffer $phpcs
) {
$this->_file = trim($file);
$this->_listeners = $listeners;
$this->tokenizers = $tokenizers;
$this->ruleset = $ruleset;
$this->restrictions = $restrictions;
$this->phpcs = $phpcs;
$cliValues = $phpcs->cli->getCommandLineValues();
if (isset($cliValues['showSources']) === true
&& $cliValues['showSources'] !== true
&& array_key_exists('summary', $cliValues['reports']) === true
&& count($cliValues['reports']) === 1
) {
$this->_recordErrors = false;
}
}//end __construct()
/**
* Sets the name of the currently active sniff.
*
* @param string $activeListener The class name of the current sniff.
*
* @return void
*/
public function setActiveListener($activeListener)
{
$this->_activeListener = $activeListener;
}//end setActiveListener()
/**
* Adds a listener to the token stack that listens to the specific tokens.
*
* When PHP_CodeSniffer encounters on the the tokens specified in $tokens,
* it invokes the process method of the sniff.
*
* @param PHP_CodeSniffer_Sniff $listener The listener to add to the
* listener stack.
* @param array(int) $tokens The token types the listener wishes to
* listen to.
*
* @return void
*/
public function addTokenListener(PHP_CodeSniffer_Sniff $listener, array $tokens)
{
foreach ($tokens as $token) {
if (isset($this->_listeners[$token]) === false) {
$this->_listeners[$token] = array();
}
if (in_array($listener, $this->_listeners[$token], true) === false) {
$this->_listeners[$token][] = $listener;
}
}
}//end addTokenListener()
/**
* Removes a listener from listening from the specified tokens.
*
* @param PHP_CodeSniffer_Sniff $listener The listener to remove from the
* listener stack.
* @param array(int) $tokens The token types the listener wishes to
* stop listen to.
*
* @return void
*/
public function removeTokenListener(
PHP_CodeSniffer_Sniff $listener,
array $tokens
) {
foreach ($tokens as $token) {
if (isset($this->_listeners[$token]) === false) {
continue;
}
if (in_array($listener, $this->_listeners[$token]) === true) {
foreach ($this->_listeners[$token] as $pos => $value) {
if ($value === $listener) {
unset($this->_listeners[$token][$pos]);
}
}
}
}
}//end removeTokenListener()
/**
* Returns the token stack for this file.
*
* @return array()
*/
public function getTokens()
{
return $this->_tokens;
}//end getTokens()
/**
* Starts the stack traversal and tells listeners when tokens are found.
*
* @param string $contents The contents to parse. If NULL, the content
* is taken from the file system.
*
* @return void
*/
public function start($contents=null)
{
$this->_parse($contents);
if (PHP_CODESNIFFER_VERBOSITY > 2) {
echo "\t*** START TOKEN PROCESSING ***".PHP_EOL;
}
$foundCode = false;
$ignoring = false;
// Foreach of the listeners that have registered to listen for this
// token, get them to process it.
foreach ($this->_tokens as $stackPtr => $token) {
// Check for ignored lines.
if ($token['code'] === T_COMMENT || $token['code'] === T_DOC_COMMENT) {
if (strpos($token['content'], '@codingStandardsIgnoreStart') !== false) {
$ignoring = true;
} else if (strpos($token['content'], '@codingStandardsIgnoreEnd') !== false) {
$ignoring = false;
// Ignore this comment too.
$this->_ignoredLines[$token['line']] = true;
} else if (strpos($token['content'], '@codingStandardsIgnoreFile') !== false) {
// Ignoring the whole file, just a little late.
$this->_errors = array();
$this->_warnings = array();
$this->_errorCount = 0;
$this->_warningCount = 0;
return;
} else if (strpos($token['content'], '@codingStandardsChangeSetting') !== false) {
$start = strpos($token['content'], '@codingStandardsChangeSetting');
$comment = substr($token['content'], $start + 30);
$parts = explode(' ', $comment);
$sniffParts = explode('.', $parts[0]);
$listenerClass = $sniffParts[0].'_Sniffs_'.$sniffParts[1].'_'.$sniffParts[2].'Sniff';
$this->phpcs->setSniffProperty($listenerClass, $parts[1], $parts[2]);
}
}
if ($ignoring === true) {
$this->_ignoredLines[$token['line']] = true;
continue;
}
if (PHP_CODESNIFFER_VERBOSITY > 2) {
$type = $token['type'];
$content = str_replace($this->eolChar, '\n', $token['content']);
echo "\t\tProcess token $stackPtr: $type => $content".PHP_EOL;
}
$tokenType = $token['code'];
if ($tokenType !== T_INLINE_HTML) {
$foundCode = true;
}
if (isset($this->_listeners[$tokenType]) === false) {
continue;
}
foreach ($this->_listeners[$tokenType] as $listenerData) {
// Make sure this sniff supports the tokenizer
// we are currently using.
$listener = $listenerData['listener'];
$class = $listenerData['class'];
if (in_array($this->tokenizerType, $listenerData['tokenizers']) === false) {
continue;
}
// If the file path matches one of our ignore patterns, skip it.
$parts = explode('_', str_replace('\\', '_', $class));
if (isset($parts[3]) === true) {
$source = $parts[0].'.'.$parts[2].'.'.substr($parts[3], 0, -5);
$patterns = $this->phpcs->getIgnorePatterns($source);
foreach ($patterns as $pattern => $type) {
// While there is support for a type of each pattern
// (absolute or relative) we don't actually support it here.
$replacements = array(
'\\,' => ',',
'*' => '.*',
);
$pattern = strtr($pattern, $replacements);
if (preg_match("|{$pattern}|i", $this->_file) === 1) {
continue(2);
}
}
}
$this->setActiveListener($class);
if (PHP_CODESNIFFER_VERBOSITY > 2) {
$startTime = microtime(true);
echo "\t\t\tProcessing ".$this->_activeListener.'... ';
}
$listener->process($this, $stackPtr);
if (PHP_CODESNIFFER_VERBOSITY > 2) {
$timeTaken = (microtime(true) - $startTime);
if (isset($this->_listenerTimes[$this->_activeListener]) === false) {
$this->_listenerTimes[$this->_activeListener] = 0;
}
$this->_listenerTimes[$this->_activeListener] += $timeTaken;
$timeTaken = round(($timeTaken), 4);
echo "DONE in $timeTaken seconds".PHP_EOL;
}
$this->_activeListener = '';
}//end foreach
}//end foreach
// Remove errors and warnings for ignored lines.
foreach ($this->_ignoredLines as $line => $ignore) {
if (isset($this->_errors[$line]) === true) {
if ($this->_recordErrors === false) {
$this->_errorCount -= $this->_errors[$line];
} else {
foreach ($this->_errors[$line] as $col => $errors) {
$this->_errorCount -= count($errors);
}
}
unset($this->_errors[$line]);
}
if (isset($this->_warnings[$line]) === true) {
if ($this->_recordErrors === false) {
$this->_errorCount -= $this->_warnings[$line];
} else {
foreach ($this->_warnings[$line] as $col => $warnings) {
$this->_warningCount -= count($warnings);
}
}
unset($this->_warnings[$line]);
}
}//end foreach
if ($this->_recordErrors === false) {
$this->_errors = array();
$this->_warnings = array();
}
// If short open tags are off but the file being checked uses
// short open tags, the whole content will be inline HTML
// and nothing will be checked. So try and handle this case.
if ($foundCode === false) {
$shortTags = (bool) ini_get('short_open_tag');
if ($shortTags === false) {
$error = 'No PHP code was found in this file and short open tags are not allowed by this install of PHP. This file may be using short open tags but PHP does not allow them.';
$this->addWarning($error, null, 'Internal.NoCodeFound');
}
}
if (PHP_CODESNIFFER_VERBOSITY > 2) {
echo "\t*** END TOKEN PROCESSING ***".PHP_EOL;
}
if (PHP_CODESNIFFER_VERBOSITY > 2) {
echo "\t*** START SNIFF PROCESSING REPORT ***".PHP_EOL;
asort($this->_listenerTimes, SORT_NUMERIC);
$this->_listenerTimes = array_reverse($this->_listenerTimes, true);
foreach ($this->_listenerTimes as $listener => $timeTaken) {
echo "\t$listener: ".round(($timeTaken), 4).' secs'.PHP_EOL;
}
echo "\t*** END SNIFF PROCESSING REPORT ***".PHP_EOL;
}
}//end start()
/**
* Remove vars stored in this sniff that are no longer required.
*
* @return void
*/
public function cleanUp()
{
$this->_tokens = null;
$this->_listeners = null;
}//end cleanUp()
/**
* Tokenizes the file and prepares it for the test run.
*
* @param string $contents The contents to parse. If NULL, the content
* is taken from the file system.
*
* @return void
*/
private function _parse($contents=null)
{
try {
$this->eolChar = self::detectLineEndings($this->_file, $contents);
} catch (PHP_CodeSniffer_Exception $e) {
$this->addWarning($e->getMessage(), null, 'Internal.DetectLineEndings');
return;
}
// Determine the tokenizer from the file extension.
$fileParts = explode('.', $this->_file);
$extension = array_pop($fileParts);
if (isset($this->tokenizers[$extension]) === true) {
$tokenizerClass = 'PHP_CodeSniffer_Tokenizers_'.$this->tokenizers[$extension];
$this->tokenizerType = $this->tokenizers[$extension];
} else {
// Revert to default.
$tokenizerClass = 'PHP_CodeSniffer_Tokenizers_'.$this->tokenizerType;
}
$tokenizer = new $tokenizerClass();
$this->tokenizer = $tokenizer;
if ($contents === null) {
$contents = file_get_contents($this->_file);
}
$this->_tokens = self::tokenizeString($contents, $tokenizer, $this->eolChar);
$this->numTokens = count($this->_tokens);
// Check for mixed line endings as these can cause tokenizer errors and we
// should let the user know that the results they get may be incorrect.
// This is done by removing all backslashes, removing the newline char we
// detected, then converting newlines chars into text. If any backslashes
// are left at the end, we have additional newline chars in use.
$contents = str_replace('\\', '', $contents);
$contents = str_replace($this->eolChar, '', $contents);
$contents = str_replace("\n", '\n', $contents);
$contents = str_replace("\r", '\r', $contents);
if (strpos($contents, '\\') !== false) {
$error = 'File has mixed line endings; this may cause incorrect results';
$this->addWarning($error, 0, 'Internal.LineEndings.Mixed');
}
if (PHP_CODESNIFFER_VERBOSITY > 0) {
if ($this->numTokens === 0) {
$numLines = 0;
} else {
$numLines = $this->_tokens[($this->numTokens - 1)]['line'];
}
echo "[$this->numTokens tokens in $numLines lines]... ";
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo PHP_EOL;
}
}
}//end _parse()
/**
* Opens a file and detects the EOL character being used.
*
* @param string $file The full path to the file.
* @param string $contents The contents to parse. If NULL, the content
* is taken from the file system.
*
* @return string
* @throws PHP_CodeSniffer_Exception If $file could not be opened.
*/
public static function detectLineEndings($file, $contents=null)
{
if ($contents === null) {
// Determine the newline character being used in this file.
// Will be either \r, \r\n or \n.
if (is_readable($file) === false) {
$error = 'Error opening file; file no longer exists or you do not have access to read the file';
throw new PHP_CodeSniffer_Exception($error);
} else {
$handle = fopen($file, 'r');
if ($handle === false) {
$error = 'Error opening file; could not auto-detect line endings';
throw new PHP_CodeSniffer_Exception($error);
}
}
$firstLine = fgets($handle);
fclose($handle);
$eolChar = substr($firstLine, -1);
if ($eolChar === "\n") {
$secondLastChar = substr($firstLine, -2, 1);
if ($secondLastChar === "\r") {
$eolChar = "\r\n";
}
} else if ($eolChar !== "\r") {
// Must not be an EOL char at the end of the line.
// Probably a one-line file, so assume \n as it really
// doesn't matter considering there are no newlines.
$eolChar = "\n";
}
} else {
if (preg_match("/\r\n?|\n/", $contents, $matches) !== 1) {
// Assuming there are no newlines.
$eolChar = "\n";
} else {
$eolChar = $matches[0];
}
}//end if
return $eolChar;
}//end detectLineEndings()
/**
* Adds an error to the error stack.
*
* @param string $error The error message.
* @param int $stackPtr The stack position where the error occurred.
* @param string $code A violation code unique to the sniff message.
* @param array $data Replacements for the error message.
* @param int $severity The severity level for this error. A value of 0
* will be converted into the default severity level.
*
* @return void
*/
public function addError($error, $stackPtr, $code='', $data=array(), $severity=0)
{
// Don't bother doing any processing if errors are just going to
// be hidden in the reports anyway.
if ($this->phpcs->cli->errorSeverity === 0) {
return;
}
// Work out which sniff generated the error.
if (substr($code, 0, 9) === 'Internal.') {
// Any internal message.
$sniff = $code;
$sniffCode = $code;
} else {
$parts = explode('_', str_replace('\\', '_', $this->_activeListener));
if (isset($parts[3]) === true) {
$sniff = $parts[0].'.'.$parts[2].'.'.$parts[3];
// Remove "Sniff" from the end.
$sniff = substr($sniff, 0, -5);
} else {
$sniff = 'unknownSniff';
}
$sniffCode = $sniff;
if ($code !== '') {
$sniffCode .= '.'.$code;
}
}//end if
// Make sure this message type is allowed based on the --sniffs
// command line argument values.
if (empty($this->restrictions) === false
&& in_array($sniffCode, $this->restrictions) === false
&& in_array($sniff, $this->restrictions) === false
) {
return;
}
// Make sure this message type has not been set to "warning".
if (isset($this->ruleset[$sniffCode]['type']) === true
&& $this->ruleset[$sniffCode]['type'] === 'warning'
) {
// Pass this off to the warning handler.
$this->addWarning($error, $stackPtr, $code, $data, $severity);
return;
}
// Make sure we are interested in this severity level.
if (isset($this->ruleset[$sniffCode]['severity']) === true) {
$severity = $this->ruleset[$sniffCode]['severity'];
} else if ($severity === 0) {
$severity = PHPCS_DEFAULT_ERROR_SEV;
}
if ($this->phpcs->cli->errorSeverity > $severity) {
return;
}
// Make sure we are not ignoring this file.
$patterns = $this->phpcs->getIgnorePatterns($sniffCode);
foreach ($patterns as $pattern => $type) {
// While there is support for a type of each pattern
// (absolute or relative) we don't actually support it here.
$replacements = array(
'\\,' => ',',
'*' => '.*',
);
$pattern = strtr($pattern, $replacements);
if (preg_match("|{$pattern}|i", $this->_file) === 1) {
return;
}
}
if ($stackPtr === null) {
$lineNum = 1;
$column = 1;
} else {
$lineNum = $this->_tokens[$stackPtr]['line'];
$column = $this->_tokens[$stackPtr]['column'];
}
$this->_errorCount++;
if ($this->_recordErrors === false) {
if (isset($this->_errors[$lineNum]) === false) {
$this->_errors[$lineNum] = 0;
}
$this->_errors[$lineNum]++;
return;
}
// Work out the warning message.
if (isset($this->ruleset[$sniffCode]['message']) === true) {
$error = $this->ruleset[$sniffCode]['message'];
}
if (empty($data) === true) {
$message = $error;
} else {
$message = vsprintf($error, $data);
}
if (isset($this->_errors[$lineNum]) === false) {
$this->_errors[$lineNum] = array();
}
if (isset($this->_errors[$lineNum][$column]) === false) {
$this->_errors[$lineNum][$column] = array();
}
$this->_errors[$lineNum][$column][] = array(
'message' => $message,
'source' => $sniffCode,
'severity' => $severity,
);
}//end addError()
/**
* Adds an warning to the warning stack.
*
* @param string $warning The error message.
* @param int $stackPtr The stack position where the error occurred.
* @param string $code A violation code unique to the sniff message.
* @param array $data Replacements for the warning message.
* @param int $severity The severity level for this warning. A value of 0
* will be converted into the default severity level.
*
* @return void
*/
public function addWarning($warning, $stackPtr, $code='', $data=array(), $severity=0)
{
// Don't bother doing any processing if warnings are just going to
// be hidden in the reports anyway.
if ($this->phpcs->cli->warningSeverity === 0) {
return;
}
// Work out which sniff generated the warning.
if (substr($code, 0, 9) === 'Internal.') {
// Any internal message.
$sniff = $code;
$sniffCode = $code;
} else {
$parts = explode('_', str_replace('\\', '_', $this->_activeListener));
if (isset($parts[3]) === true) {
$sniff = $parts[0].'.'.$parts[2].'.'.$parts[3];
// Remove "Sniff" from the end.
$sniff = substr($sniff, 0, -5);
} else {
$sniff = 'unknownSniff';
}
$sniffCode = $sniff;
if ($code !== '') {
$sniffCode .= '.'.$code;
}
}//end if
// Make sure this message type is allowed based on the --sniffs
// command line argument values.
if (empty($this->restrictions) === false
&& in_array($sniffCode, $this->restrictions) === false
&& in_array($sniff, $this->restrictions) === false
) {
return;
}
// Make sure this message type has not been set to "error".
if (isset($this->ruleset[$sniffCode]['type']) === true
&& $this->ruleset[$sniffCode]['type'] === 'error'
) {
// Pass this off to the error handler.
$this->addError($warning, $stackPtr, $code, $data, $severity);
return;
}
// Make sure we are interested in this severity level.
if (isset($this->ruleset[$sniffCode]['severity']) === true) {
$severity = $this->ruleset[$sniffCode]['severity'];
} else if ($severity === 0) {
$severity = PHPCS_DEFAULT_WARN_SEV;
}
if ($this->phpcs->cli->warningSeverity > $severity) {
return;
}
// Make sure we are not ignoring this file.
$patterns = $this->phpcs->getIgnorePatterns($sniffCode);
foreach ($patterns as $pattern => $type) {
// While there is support for a type of each pattern
// (absolute or relative) we don't actually support it here.
$replacements = array(
'\\,' => ',',
'*' => '.*',
);
$pattern = strtr($pattern, $replacements);
if (preg_match("|{$pattern}|i", $this->_file) === 1) {
return;
}
}
if ($stackPtr === null) {
$lineNum = 1;
$column = 1;
} else {
$lineNum = $this->_tokens[$stackPtr]['line'];
$column = $this->_tokens[$stackPtr]['column'];
}
$this->_warningCount++;
if ($this->_recordErrors === false) {
if (isset($this->_warnings[$lineNum]) === false) {
$this->_warnings[$lineNum] = 0;
}
$this->_warnings[$lineNum]++;
return;
}
// Work out the warning message.
if (isset($this->ruleset[$sniffCode]['message']) === true) {
$warning = $this->ruleset[$sniffCode]['message'];
}
if (empty($data) === true) {
$message = $warning;
} else {
$message = vsprintf($warning, $data);
}
if (isset($this->_warnings[$lineNum]) === false) {
$this->_warnings[$lineNum] = array();
}
if (isset($this->_warnings[$lineNum][$column]) === false) {
$this->_warnings[$lineNum][$column] = array();
}
$this->_warnings[$lineNum][$column][] = array(
'message' => $message,
'source' => $sniffCode,
'severity' => $severity,
);
}//end addWarning()
/**
* Returns the number of errors raised.
*
* @return int
*/
public function getErrorCount()
{
return $this->_errorCount;
}//end getErrorCount()
/**
* Returns the number of warnings raised.
*