forked from squizlabs/PHP_CodeSniffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
File.php
2489 lines (2136 loc) · 82.8 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
/**
* Represents a piece of content being checked during the run.
*
* @author Greg Sherwood <[email protected]>
* @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\Files;
use PHP_CodeSniffer\Ruleset;
use PHP_CodeSniffer\Config;
use PHP_CodeSniffer\Fixer;
use PHP_CodeSniffer\Util;
use PHP_CodeSniffer\Exceptions\RuntimeException;
use PHP_CodeSniffer\Exceptions\TokenizerException;
class File
{
/**
* The absolute path to the file associated with this object.
*
* @var string
*/
public $path = '';
/**
* The absolute path to the file associated with this object.
*
* @var string
*/
protected $content = '';
/**
* The config data for the run.
*
* @var \PHP_CodeSniffer\Config
*/
public $config = null;
/**
* The ruleset used for the run.
*
* @var \PHP_CodeSniffer\Ruleset
*/
public $ruleset = null;
/**
* If TRUE, the entire file is being ignored.
*
* @var boolean
*/
public $ignored = false;
/**
* The EOL character this file uses.
*
* @var string
*/
public $eolChar = '';
/**
* The Fixer object to control fixing errors.
*
* @var \PHP_CodeSniffer\Fixer
*/
public $fixer = null;
/**
* The tokenizer being used for this file.
*
* @var \PHP_CodeSniffer\Tokenizers\Tokenizer
*/
public $tokenizer = null;
/**
* The name of the tokenizer being used for this file.
*
* @var string
*/
public $tokenizerType = 'PHP';
/**
* Was the file loaded from cache?
*
* If TRUE, the file was loaded from a local cache.
* If FALSE, the file was tokenized and processed fully.
*
* @var boolean
*/
public $fromCache = false;
/**
* The number of tokens in this file.
*
* Stored here to save calling count() everywhere.
*
* @var integer
*/
public $numTokens = 0;
/**
* The tokens stack map.
*
* @var array
*/
protected $tokens = [];
/**
* The errors raised from sniffs.
*
* @var array
* @see getErrors()
*/
protected $errors = [];
/**
* The warnings raised from sniffs.
*
* @var array
* @see getWarnings()
*/
protected $warnings = [];
/**
* The metrics recorded by sniffs.
*
* @var array
* @see getMetrics()
*/
protected $metrics = [];
/**
* The metrics recorded for each token.
*
* Stops the same metric being recorded for the same token twice.
*
* @var array
* @see getMetrics()
*/
private $metricTokens = [];
/**
* The total number of errors raised.
*
* @var integer
*/
protected $errorCount = 0;
/**
* The total number of warnings raised.
*
* @var integer
*/
protected $warningCount = 0;
/**
* The total number of errors and warnings that can be fixed.
*
* @var integer
*/
protected $fixableCount = 0;
/**
* The total number of errors and warnings that were fixed.
*
* @var integer
*/
protected $fixedCount = 0;
/**
* An array of sniffs that are being ignored.
*
* @var array
*/
protected $ignoredListeners = [];
/**
* An array of message codes that are being ignored.
*
* @var array
*/
protected $ignoredCodes = [];
/**
* An array of sniffs listening to this file's processing.
*
* @var \PHP_CodeSniffer\Sniffs\Sniff[]
*/
protected $listeners = [];
/**
* The class name of the sniff currently processing the file.
*
* @var string
*/
protected $activeListener = '';
/**
* An array of sniffs being processed and how long they took.
*
* @var array
*/
protected $listenerTimes = [];
/**
* A cache of often used config settings to improve performance.
*
* Storing them here saves 10k+ calls to __get() in the Config class.
*
* @var array
*/
protected $configCache = [];
/**
* Constructs a file.
*
* @param string $path The absolute path to the file to process.
* @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run.
* @param \PHP_CodeSniffer\Config $config The config data for the run.
*
* @return void
*/
public function __construct($path, Ruleset $ruleset, Config $config)
{
$this->path = $path;
$this->ruleset = $ruleset;
$this->config = $config;
$this->fixer = new Fixer();
$parts = explode('.', $path);
$extension = array_pop($parts);
if (isset($config->extensions[$extension]) === true) {
$this->tokenizerType = $config->extensions[$extension];
} else {
// Revert to default.
$this->tokenizerType = 'PHP';
}
$this->configCache['cache'] = $this->config->cache;
$this->configCache['sniffs'] = array_map('strtolower', $this->config->sniffs);
$this->configCache['exclude'] = array_map('strtolower', $this->config->exclude);
$this->configCache['errorSeverity'] = $this->config->errorSeverity;
$this->configCache['warningSeverity'] = $this->config->warningSeverity;
$this->configCache['recordErrors'] = $this->config->recordErrors;
$this->configCache['ignorePatterns'] = $this->ruleset->ignorePatterns;
$this->configCache['includePatterns'] = $this->ruleset->includePatterns;
}//end __construct()
/**
* Set the content of the file.
*
* Setting the content also calculates the EOL char being used.
*
* @param string $content The file content.
*
* @return void
*/
public function setContent($content)
{
$this->content = $content;
$this->tokens = [];
try {
$this->eolChar = Util\Common::detectLineEndings($content);
} catch (RuntimeException $e) {
$this->addWarningOnLine($e->getMessage(), 1, 'Internal.DetectLineEndings');
return;
}
}//end setContent()
/**
* Reloads the content of the file.
*
* By default, we have no idea where our content comes from,
* so we can't do anything.
*
* @return void
*/
public function reloadContent()
{
}//end reloadContent()
/**
* Disables caching of this file.
*
* @return void
*/
public function disableCaching()
{
$this->configCache['cache'] = false;
}//end disableCaching()
/**
* Starts the stack traversal and tells listeners when tokens are found.
*
* @return void
*/
public function process()
{
if ($this->ignored === true) {
return;
}
$this->errors = [];
$this->warnings = [];
$this->errorCount = 0;
$this->warningCount = 0;
$this->fixableCount = 0;
$this->parse();
// Check if tokenizer errors cause this file to be ignored.
if ($this->ignored === true) {
return;
}
$this->fixer->startFile($this);
if (PHP_CODESNIFFER_VERBOSITY > 2) {
echo "\t*** START TOKEN PROCESSING ***".PHP_EOL;
}
$foundCode = false;
$listenerIgnoreTo = [];
$inTests = defined('PHP_CODESNIFFER_IN_TESTS');
$checkAnnotations = $this->config->annotations;
// 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 ($checkAnnotations === true
&& ($token['code'] === T_COMMENT
|| $token['code'] === T_PHPCS_IGNORE_FILE
|| $token['code'] === T_PHPCS_SET
|| $token['code'] === T_DOC_COMMENT_STRING
|| $token['code'] === T_DOC_COMMENT_TAG
|| ($inTests === true && $token['code'] === T_INLINE_HTML))
) {
$commentText = ltrim($this->tokens[$stackPtr]['content'], ' /*');
$commentTextLower = strtolower($commentText);
if (strpos($commentText, '@codingStandards') !== false) {
if (strpos($commentText, '@codingStandardsIgnoreFile') !== false) {
// Ignoring the whole file, just a little late.
$this->errors = [];
$this->warnings = [];
$this->errorCount = 0;
$this->warningCount = 0;
$this->fixableCount = 0;
return;
} else if (strpos($commentText, '@codingStandardsChangeSetting') !== false) {
$start = strpos($commentText, '@codingStandardsChangeSetting');
$comment = substr($commentText, ($start + 30));
$parts = explode(' ', $comment);
if (count($parts) >= 2) {
$sniffParts = explode('.', $parts[0]);
if (count($sniffParts) >= 3) {
// If the sniff code is not known to us, it has not been registered in this run.
// But don't throw an error as it could be there for a different standard to use.
if (isset($this->ruleset->sniffCodes[$parts[0]]) === true) {
$listenerCode = array_shift($parts);
$propertyCode = array_shift($parts);
$propertyValue = rtrim(implode(' ', $parts), " */\r\n");
$listenerClass = $this->ruleset->sniffCodes[$listenerCode];
$this->ruleset->setSniffProperty($listenerClass, $propertyCode, $propertyValue);
}
}
}
}//end if
} else if (substr($commentTextLower, 0, 16) === 'phpcs:ignorefile'
|| substr($commentTextLower, 0, 17) === '@phpcs:ignorefile'
) {
// Ignoring the whole file, just a little late.
$this->errors = [];
$this->warnings = [];
$this->errorCount = 0;
$this->warningCount = 0;
$this->fixableCount = 0;
return;
} else if (substr($commentTextLower, 0, 9) === 'phpcs:set'
|| substr($commentTextLower, 0, 10) === '@phpcs:set'
) {
if (isset($token['sniffCode']) === true) {
$listenerCode = $token['sniffCode'];
if (isset($this->ruleset->sniffCodes[$listenerCode]) === true) {
$propertyCode = $token['sniffProperty'];
$propertyValue = $token['sniffPropertyValue'];
$listenerClass = $this->ruleset->sniffCodes[$listenerCode];
$this->ruleset->setSniffProperty($listenerClass, $propertyCode, $propertyValue);
}
}
}//end if
}//end if
if (PHP_CODESNIFFER_VERBOSITY > 2) {
$type = $token['type'];
$content = Util\Common::prepareForOutput($token['content']);
echo "\t\tProcess token $stackPtr: $type => $content".PHP_EOL;
}
if ($token['code'] !== T_INLINE_HTML) {
$foundCode = true;
}
if (isset($this->ruleset->tokenListeners[$token['code']]) === false) {
continue;
}
foreach ($this->ruleset->tokenListeners[$token['code']] as $listenerData) {
if (isset($this->ignoredListeners[$listenerData['class']]) === true
|| (isset($listenerIgnoreTo[$listenerData['class']]) === true
&& $listenerIgnoreTo[$listenerData['class']] > $stackPtr)
) {
// This sniff is ignoring past this token, or the whole file.
continue;
}
// Make sure this sniff supports the tokenizer
// we are currently using.
$class = $listenerData['class'];
if (isset($listenerData['tokenizers'][$this->tokenizerType]) === false) {
continue;
}
// If the file path matches one of our ignore patterns, skip it.
// While there is support for a type of each pattern
// (absolute or relative) we don't actually support it here.
foreach ($listenerData['ignore'] as $pattern) {
// We assume a / directory separator, as do the exclude rules
// most developers write, so we need a special case for any system
// that is different.
if (DIRECTORY_SEPARATOR === '\\') {
$pattern = str_replace('/', '\\\\', $pattern);
}
$pattern = '`'.$pattern.'`i';
if (preg_match($pattern, $this->path) === 1) {
$this->ignoredListeners[$class] = true;
continue(2);
}
}
// If the file path does not match one of our include patterns, skip it.
// While there is support for a type of each pattern
// (absolute or relative) we don't actually support it here.
if (empty($listenerData['include']) === false) {
$included = false;
foreach ($listenerData['include'] as $pattern) {
// We assume a / directory separator, as do the exclude rules
// most developers write, so we need a special case for any system
// that is different.
if (DIRECTORY_SEPARATOR === '\\') {
$pattern = str_replace('/', '\\\\', $pattern);
}
$pattern = '`'.$pattern.'`i';
if (preg_match($pattern, $this->path) === 1) {
$included = true;
break;
}
}
if ($included === false) {
$this->ignoredListeners[$class] = true;
continue;
}
}//end if
$this->activeListener = $class;
if (PHP_CODESNIFFER_VERBOSITY > 2) {
$startTime = microtime(true);
echo "\t\t\tProcessing ".$this->activeListener.'... ';
}
$ignoreTo = $this->ruleset->sniffs[$class]->process($this, $stackPtr);
if ($ignoreTo !== null) {
$listenerIgnoreTo[$this->activeListener] = $ignoreTo;
}
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
// 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.
// We don't show this error for STDIN because we can't be sure the content
// actually came directly from the user. It could be something like
// refs from a Git pre-push hook.
if ($foundCode === false && $this->tokenizerType === 'PHP' && $this->path !== 'STDIN') {
$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;
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;
}
$this->fixedCount += $this->fixer->getFixCount();
}//end process()
/**
* Tokenizes the file and prepares it for the test run.
*
* @return void
*/
public function parse()
{
if (empty($this->tokens) === false) {
// File has already been parsed.
return;
}
try {
$tokenizerClass = 'PHP_CodeSniffer\Tokenizers\\'.$this->tokenizerType;
$this->tokenizer = new $tokenizerClass($this->content, $this->config, $this->eolChar);
$this->tokens = $this->tokenizer->getTokens();
} catch (TokenizerException $e) {
$this->ignored = true;
$this->addWarning($e->getMessage(), null, 'Internal.Tokenizer.Exception');
if (PHP_CODESNIFFER_VERBOSITY > 0) {
echo "[$this->tokenizerType => tokenizer error]... ";
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo PHP_EOL;
}
}
return;
}
$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('\\', '', $this->content);
$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->addWarningOnLine($error, 1, 'Internal.LineEndings.Mixed');
}
if (PHP_CODESNIFFER_VERBOSITY > 0) {
if ($this->numTokens === 0) {
$numLines = 0;
} else {
$numLines = $this->tokens[($this->numTokens - 1)]['line'];
}
echo "[$this->tokenizerType => $this->numTokens tokens in $numLines lines]... ";
if (PHP_CODESNIFFER_VERBOSITY > 1) {
echo PHP_EOL;
}
}
}//end parse()
/**
* Returns the token stack for this file.
*
* @return array
*/
public function getTokens()
{
return $this->tokens;
}//end getTokens()
/**
* Remove vars stored in this file that are no longer required.
*
* @return void
*/
public function cleanUp()
{
$this->listenerTimes = null;
$this->content = null;
$this->tokens = null;
$this->metricTokens = null;
$this->tokenizer = null;
$this->fixer = null;
$this->config = null;
$this->ruleset = null;
}//end cleanUp()
/**
* Records an error against a specific token in the file.
*
* @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.
* @param boolean $fixable Can the error be fixed by the sniff?
*
* @return boolean
*/
public function addError(
$error,
$stackPtr,
$code,
$data=[],
$severity=0,
$fixable=false
) {
if ($stackPtr === null) {
$line = 1;
$column = 1;
} else {
$line = $this->tokens[$stackPtr]['line'];
$column = $this->tokens[$stackPtr]['column'];
}
return $this->addMessage(true, $error, $line, $column, $code, $data, $severity, $fixable);
}//end addError()
/**
* Records a warning against a specific token in the file.
*
* @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.
* @param boolean $fixable Can the warning be fixed by the sniff?
*
* @return boolean
*/
public function addWarning(
$warning,
$stackPtr,
$code,
$data=[],
$severity=0,
$fixable=false
) {
if ($stackPtr === null) {
$line = 1;
$column = 1;
} else {
$line = $this->tokens[$stackPtr]['line'];
$column = $this->tokens[$stackPtr]['column'];
}
return $this->addMessage(false, $warning, $line, $column, $code, $data, $severity, $fixable);
}//end addWarning()
/**
* Records an error against a specific line in the file.
*
* @param string $error The error message.
* @param int $line The line on which 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 boolean
*/
public function addErrorOnLine(
$error,
$line,
$code,
$data=[],
$severity=0
) {
return $this->addMessage(true, $error, $line, 1, $code, $data, $severity, false);
}//end addErrorOnLine()
/**
* Records a warning against a specific token in the file.
*
* @param string $warning The error message.
* @param int $line The line on which the warning 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
* will be converted into the default severity level.
*
* @return boolean
*/
public function addWarningOnLine(
$warning,
$line,
$code,
$data=[],
$severity=0
) {
return $this->addMessage(false, $warning, $line, 1, $code, $data, $severity, false);
}//end addWarningOnLine()
/**
* Records a fixable error against a specific token in the file.
*
* Returns true if the error was recorded and should be fixed.
*
* @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 boolean
*/
public function addFixableError(
$error,
$stackPtr,
$code,
$data=[],
$severity=0
) {
$recorded = $this->addError($error, $stackPtr, $code, $data, $severity, true);
if ($recorded === true && $this->fixer->enabled === true) {
return true;
}
return false;
}//end addFixableError()
/**
* Records a fixable warning against a specific token in the file.
*
* Returns true if the warning was recorded and should be fixed.
*
* @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 boolean
*/
public function addFixableWarning(
$warning,
$stackPtr,
$code,
$data=[],
$severity=0
) {
$recorded = $this->addWarning($warning, $stackPtr, $code, $data, $severity, true);
if ($recorded === true && $this->fixer->enabled === true) {
return true;
}
return false;
}//end addFixableWarning()
/**
* Adds an error to the error stack.
*
* @param boolean $error Is this an error message?
* @param string $message The text of the message.
* @param int $line The line on which the message occurred.
* @param int $column The column at which the message occurred.
* @param string $code A violation code unique to the sniff message.
* @param array $data Replacements for the message.
* @param int $severity The severity level for this message. A value of 0
* will be converted into the default severity level.
* @param boolean $fixable Can the problem be fixed by the sniff?
*
* @return boolean
*/
protected function addMessage($error, $message, $line, $column, $code, $data, $severity, $fixable)
{
// Check if this line is ignoring all message codes.
if (isset($this->tokenizer->ignoredLines[$line]['.all']) === true) {
return false;
}
// Work out which sniff generated the message.
$parts = explode('.', $code);
if ($parts[0] === 'Internal') {
// An internal message.
$listenerCode = Util\Common::getSniffCode($this->activeListener);
$sniffCode = $code;
$checkCodes = [$sniffCode];
} else {
if ($parts[0] !== $code) {
// The full message code has been passed in.
$sniffCode = $code;
$listenerCode = substr($sniffCode, 0, strrpos($sniffCode, '.'));
} else {
$listenerCode = Util\Common::getSniffCode($this->activeListener);
$sniffCode = $listenerCode.'.'.$code;
$parts = explode('.', $sniffCode);
}
$checkCodes = [
$sniffCode,
$parts[0].'.'.$parts[1].'.'.$parts[2],
$parts[0].'.'.$parts[1],
$parts[0],
];
}//end if
if (isset($this->tokenizer->ignoredLines[$line]) === true) {
// Check if this line is ignoring this specific message.
$ignored = false;
foreach ($checkCodes as $checkCode) {
if (isset($this->tokenizer->ignoredLines[$line][$checkCode]) === true) {
$ignored = true;
break;
}
}
// If it is ignored, make sure it's not whitelisted.
if ($ignored === true
&& isset($this->tokenizer->ignoredLines[$line]['.except']) === true
) {
foreach ($checkCodes as $checkCode) {
if (isset($this->tokenizer->ignoredLines[$line]['.except'][$checkCode]) === true) {
$ignored = false;
break;
}
}
}
if ($ignored === true) {
return false;
}
}//end if
$includeAll = true;
if ($this->configCache['cache'] === false
|| $this->configCache['recordErrors'] === false
) {
$includeAll = false;
}
// Filter out any messages for sniffs that shouldn't have run
// due to the use of the --sniffs command line argument.
if ($includeAll === false
&& ((empty($this->configCache['sniffs']) === false
&& in_array(strtolower($listenerCode), $this->configCache['sniffs'], true) === false)
|| (empty($this->configCache['exclude']) === false
&& in_array(strtolower($listenerCode), $this->configCache['exclude'], true) === true))
) {
return false;
}
// If we know this sniff code is being ignored for this file, return early.
foreach ($checkCodes as $checkCode) {
if (isset($this->ignoredCodes[$checkCode]) === true) {
return false;
}
}
$oppositeType = 'warning';
if ($error === false) {
$oppositeType = 'error';
}
foreach ($checkCodes as $checkCode) {
// Make sure this message type has not been set to the opposite message type.
if (isset($this->ruleset->ruleset[$checkCode]['type']) === true
&& $this->ruleset->ruleset[$checkCode]['type'] === $oppositeType
) {
$error = !$error;
break;
}
}
if ($error === true) {
$configSeverity = $this->configCache['errorSeverity'];
$messageCount = &$this->errorCount;
$messages = &$this->errors;
} else {
$configSeverity = $this->configCache['warningSeverity'];
$messageCount = &$this->warningCount;
$messages = &$this->warnings;
}
if ($includeAll === false && $configSeverity === 0) {
// Don't bother doing any processing as these messages are just going to
// be hidden in the reports anyway.
return false;
}
if ($severity === 0) {
$severity = 5;
}
foreach ($checkCodes as $checkCode) {
// Make sure we are interested in this severity level.
if (isset($this->ruleset->ruleset[$checkCode]['severity']) === true) {
$severity = $this->ruleset->ruleset[$checkCode]['severity'];
break;
}
}
if ($includeAll === false && $configSeverity > $severity) {
return false;
}
// Make sure we are not ignoring this file.
$included = null;
foreach ($checkCodes as $checkCode) {
$patterns = null;
if (isset($this->configCache['includePatterns'][$checkCode]) === true) {
$patterns = $this->configCache['includePatterns'][$checkCode];
$excluding = false;
} else if (isset($this->configCache['ignorePatterns'][$checkCode]) === true) {
$patterns = $this->configCache['ignorePatterns'][$checkCode];
$excluding = true;
}
if ($patterns === null) {
continue;
}
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 = [
'\\,' => ',',
'*' => '.*',
];
// We assume a / directory separator, as do the exclude rules
// most developers write, so we need a special case for any system
// that is different.
if (DIRECTORY_SEPARATOR === '\\') {
$replacements['/'] = '\\\\';
}
$pattern = '`'.strtr($pattern, $replacements).'`i';
$matched = preg_match($pattern, $this->path);
if ($matched === 0) {
if ($excluding === false && $included === null) {
// This file path is not being included.
$included = false;
}
continue;