-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathVariableAnalysisSniff.php
More file actions
1425 lines (1299 loc) · 44.8 KB
/
VariableAnalysisSniff.php
File metadata and controls
1425 lines (1299 loc) · 44.8 KB
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
namespace VariableAnalysis\Sniffs\CodeAnalysis;
use VariableAnalysis\Lib\ScopeInfo;
use VariableAnalysis\Lib\VariableInfo;
use VariableAnalysis\Lib\Constants;
use VariableAnalysis\Lib\Helpers;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
class VariableAnalysisSniff implements Sniff {
/**
* The current phpcsFile being checked.
*
* @var File|null phpcsFile
*/
protected $currentFile = null;
/**
* A list of scopes encountered so far and the variables within them.
*
* @var ScopeInfo[]
*/
private $scopes = [];
/**
* A list of custom functions which pass in variables to be initialized by
* reference (eg `preg_match()`) and therefore should not require those
* variables to be defined ahead of time. The list is space separated and
* each entry is of the form `functionName:1,2`. The function name comes
* first followed by a colon and a comma-separated list of argument numbers
* (starting from 1) which should be considered variable definitions. The
* special value `...` in the arguments list will cause all arguments after
* the last number to be considered variable definitions.
*
* @var string|null
*/
public $sitePassByRefFunctions = null;
/**
* If set, allows common WordPress pass-by-reference functions in addition to
* the standard PHP ones.
*
* @var bool
*/
public $allowWordPressPassByRefFunctions = false;
/**
* Allow exceptions in a catch block to be unused without warning.
*
* @var bool
*/
public $allowUnusedCaughtExceptions = true;
/**
* Allow function parameters to be unused without provoking unused-var warning.
* Set generic.codeanalysis.variableanalysis.allowUnusedFunctionParameters to a true value.
*
* @var bool
*/
public $allowUnusedFunctionParameters = false;
/**
* A space-separated list of names of placeholder variables that you want to
* ignore from unused variable warnings. For example, to ignore the variables
* `$junk` and `$unused`, this could be set to `'junk unused'`.
*
* @var string|null
*/
public $validUnusedVariableNames = null;
/**
* A PHP regexp string for variables that you want to ignore from unused
* variable warnings. For example, to ignore the variables `$_junk` and
* `$_unused`, this could be set to `'/^_/'`.
*
* @var string|null
*/
public $ignoreUnusedRegexp = null;
/**
* A space-separated list of names of placeholder variables that you want to
* ignore from undefined variable warnings. For example, to ignore the variables
* `$post` and `$undefined`, this could be set to `'post undefined'`.
*
* @var string|null
*/
public $validUndefinedVariableNames = null;
/**
* Allows unused arguments in a function definition if they are
* followed by an argument which is used.
*
* @var bool
*/
public $allowUnusedParametersBeforeUsed = true;
/**
* If set to true, unused keys or values created by the `as` statement
* in a `foreach` loop will never be marked as unused.
*
* @var bool
*/
public $allowUnusedForeachVariables = true;
/**
* @return (int|string)[]
*/
public function register() {
return [
T_VARIABLE,
T_DOUBLE_QUOTED_STRING,
T_HEREDOC,
T_CLOSE_CURLY_BRACKET,
T_STRING,
];
}
/**
* @param string $functionName
*
* @return string[]
*/
private function getPassByReferenceFunction($functionName) {
$passByRefFunctions = Constants::getPassByReferenceFunctions();
if (!empty($this->sitePassByRefFunctions)) {
$lines = Helpers::splitStringToArray('/\s+/', trim($this->sitePassByRefFunctions));
foreach ($lines as $line) {
list ($function, $args) = explode(':', $line);
$passByRefFunctions[$function] = explode(',', $args);
}
}
if ($this->allowWordPressPassByRefFunctions) {
$passByRefFunctions = array_merge($passByRefFunctions, Constants::getWordPressPassByReferenceFunctions());
}
return isset($passByRefFunctions[$functionName]) ? $passByRefFunctions[$functionName] : [];
}
/**
* @param File $phpcsFile
* @param int $stackPtr
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr) {
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
if ($this->currentFile !== $phpcsFile) {
$this->currentFile = $phpcsFile;
}
if ($token['code'] === T_VARIABLE) {
$this->processVariable($phpcsFile, $stackPtr);
return;
}
if (($token['code'] === T_DOUBLE_QUOTED_STRING) || ($token['code'] === T_HEREDOC)) {
$this->processVariableInString($phpcsFile, $stackPtr);
return;
}
if (($token['code'] === T_STRING) && ($token['content'] === 'compact')) {
$this->processCompact($phpcsFile, $stackPtr);
return;
}
if ($this->isGetDefinedVars($phpcsFile, $stackPtr)) {
Helpers::debug('get_defined_vars is being called');
$this->markAllVariablesRead($phpcsFile, $stackPtr);
return;
}
if (($token['code'] === T_CLOSE_CURLY_BRACKET) && isset($token['scope_condition'])) {
$this->processScopeClose($phpcsFile, $token['scope_condition']);
return;
}
}
/**
* @param File $phpcsFile
* @param int $stackPtr
*
* @return bool
*/
protected function isGetDefinedVars(File $phpcsFile, $stackPtr) {
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
if (! $token || $token['content'] !== 'get_defined_vars') {
return false;
}
// Make sure this is a function call
$parenPointer = $phpcsFile->findNext([T_OPEN_PARENTHESIS], $stackPtr, $stackPtr + 2);
if (! $parenPointer) {
return false;
}
return true;
}
/**
* @param int $currScope
*
* @return string
*/
protected function getScopeKey($currScope) {
return ($this->currentFile ? $this->currentFile->getFilename() : 'unknown file') . ':' . $currScope;
}
/**
* @param int $currScope
*
* @return ScopeInfo|null
*/
protected function getScopeInfo($currScope) {
$scopeKey = $this->getScopeKey($currScope);
return isset($this->scopes[$scopeKey]) ? $this->scopes[$scopeKey] : null;
}
/**
* @param int $currScope
*
* @return ScopeInfo
*/
protected function getOrCreateScopeInfo($currScope) {
$scopeKey = $this->getScopeKey($currScope);
if (!isset($this->scopes[$scopeKey])) {
$this->scopes[$scopeKey] = new ScopeInfo($currScope);
}
return $this->scopes[$scopeKey];
}
/**
* @param string $varName
* @param int $currScope
*
* @return VariableInfo|null
*/
protected function getVariableInfo($varName, $currScope) {
$scopeInfo = $this->getScopeInfo($currScope);
return ( $scopeInfo && isset($scopeInfo->variables[$varName]) ) ? $scopeInfo->variables[$varName] : null;
}
/**
* @param string $varName
* @param int $currScope
*
* @return VariableInfo
*/
protected function getOrCreateVariableInfo($varName, $currScope) {
$scopeInfo = $this->getOrCreateScopeInfo($currScope);
if (!isset($scopeInfo->variables[$varName])) {
$scopeInfo->variables[$varName] = new VariableInfo($varName);
$validUnusedVariableNames = (empty($this->validUnusedVariableNames))
? []
: Helpers::splitStringToArray('/\s+/', trim($this->validUnusedVariableNames));
$validUndefinedVariableNames = (empty($this->validUndefinedVariableNames))
? []
: Helpers::splitStringToArray('/\s+/', trim($this->validUndefinedVariableNames));
if (in_array($varName, $validUnusedVariableNames)) {
$scopeInfo->variables[$varName]->ignoreUnused = true;
}
if (isset($this->ignoreUnusedRegexp) && preg_match($this->ignoreUnusedRegexp, $varName) === 1) {
$scopeInfo->variables[$varName]->ignoreUnused = true;
}
if (in_array($varName, $validUndefinedVariableNames)) {
$scopeInfo->variables[$varName]->ignoreUndefined = true;
}
}
return $scopeInfo->variables[$varName];
}
/**
* @param VariableInfo $varInfo
* @param ScopeInfo $scopeInfo
*
* @return bool
*/
protected function areFollowingArgumentsUsed($varInfo, $scopeInfo) {
$foundVarPosition = false;
foreach ($scopeInfo->variables as $variable) {
if ($variable === $varInfo) {
$foundVarPosition = true;
continue;
}
if (! $foundVarPosition) {
continue;
}
if ($variable->firstRead) {
return true;
}
}
return false;
}
/**
* @param string $varName
* @param int $stackPtr
* @param int $currScope
*
* @return void
*/
protected function markVariableAssignment($varName, $stackPtr, $currScope) {
$varInfo = $this->getOrCreateVariableInfo($varName, $currScope);
if (!isset($varInfo->scopeType)) {
$varInfo->scopeType = 'local';
}
if (isset($varInfo->firstInitialized) && ($varInfo->firstInitialized <= $stackPtr)) {
return;
}
$varInfo->firstInitialized = $stackPtr;
}
/**
* @param string $varName
* @param string $scopeType
* @param ?string $typeHint
* @param int $stackPtr
* @param int $currScope
* @param ?bool $permitMatchingRedeclaration
*
* @return void
*/
protected function markVariableDeclaration(
$varName,
$scopeType,
$typeHint,
$stackPtr,
$currScope,
$permitMatchingRedeclaration = false
) {
$varInfo = $this->getOrCreateVariableInfo($varName, $currScope);
if (isset($varInfo->scopeType)) {
if (($permitMatchingRedeclaration === false) || ($varInfo->scopeType !== $scopeType)) {
// Issue redeclaration/reuse warning
// Note: we check off scopeType not firstDeclared, this is so that
// we catch declarations that come after implicit declarations like
// use of a variable as a local.
$this->addWarning(
"Redeclaration of %s %s as %s.",
$stackPtr,
'VariableRedeclaration',
[
VariableInfo::$scopeTypeDescriptions[$varInfo->scopeType],
"\${$varName}",
VariableInfo::$scopeTypeDescriptions[$scopeType],
]
);
}
}
$varInfo->scopeType = $scopeType;
if (isset($typeHint)) {
$varInfo->typeHint = $typeHint;
}
if (isset($varInfo->firstDeclared) && ($varInfo->firstDeclared <= $stackPtr)) {
return;
}
$varInfo->firstDeclared = $stackPtr;
}
/**
* @param string $message
* @param int $stackPtr
* @param string $code
* @param string[] $data
*
* @return void
*/
protected function addWarning($message, $stackPtr, $code, $data) {
if (! $this->currentFile) {
throw new \Exception('Cannot add warning; current file is not set.');
}
$this->currentFile->addWarning(
$message,
$stackPtr,
$code,
$data
);
}
/**
* @param string $varName
* @param int $stackPtr
* @param int $currScope
*
* @return void
*/
protected function markVariableRead($varName, $stackPtr, $currScope) {
$varInfo = $this->getOrCreateVariableInfo($varName, $currScope);
if (isset($varInfo->firstRead) && ($varInfo->firstRead <= $stackPtr)) {
return;
}
$varInfo->firstRead = $stackPtr;
}
/**
* @param string $varName
* @param int $stackPtr
* @param int $currScope
*
* @return bool
*/
protected function isVariableUndefined($varName, $stackPtr, $currScope) {
$varInfo = $this->getOrCreateVariableInfo($varName, $currScope);
if ($varInfo->ignoreUndefined) {
return false;
}
if (isset($varInfo->firstDeclared) && $varInfo->firstDeclared <= $stackPtr) {
return false;
}
if (isset($varInfo->firstInitialized) && $varInfo->firstInitialized <= $stackPtr) {
return false;
}
return true;
}
/**
* @param File $phpcsFile
* @param string $varName
* @param int $stackPtr
* @param int $currScope
*
* @return void
*/
protected function markVariableReadAndWarnIfUndefined($phpcsFile, $varName, $stackPtr, $currScope) {
$this->markVariableRead($varName, $stackPtr, $currScope);
if ($this->isVariableUndefined($varName, $stackPtr, $currScope) === true) {
Helpers::debug("variable $varName looks undefined");
$phpcsFile->addWarning(
"Variable %s is undefined.",
$stackPtr,
'UndefinedVariable',
["\${$varName}"]
);
}
}
/**
* @param File $phpcsFile
* @param int $stackPtr
*
* @return void
*/
protected function markAllVariablesRead(File $phpcsFile, $stackPtr) {
$currScope = Helpers::findVariableScope($phpcsFile, $stackPtr);
if ($currScope === null) {
return;
}
$scopeInfo = $this->getOrCreateScopeInfo($currScope);
$count = count($scopeInfo->variables);
Helpers::debug("marking all $count variables in scope as read");
foreach ($scopeInfo->variables as $varInfo) {
$this->markVariableRead($varInfo->name, $stackPtr, $scopeInfo->owner);
}
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $currScope
*
* @return bool
*/
protected function checkForFunctionPrototype(File $phpcsFile, $stackPtr, $varName, $currScope) {
$tokens = $phpcsFile->getTokens();
// Are we a function or closure parameter?
// It would be nice to get the list of function parameters from watching for
// T_FUNCTION, but AbstractVariableSniff and AbstractScopeSniff define everything
// we need to do that as private or final, so we have to do it this hackish way.
$openPtr = Helpers::findContainingOpeningBracket($phpcsFile, $stackPtr);
if (! is_int($openPtr)) {
return false;
}
$functionPtr = Helpers::findPreviousFunctionPtr($phpcsFile, $openPtr);
if (// phpcs:ignore PSR2.ControlStructures.ControlStructureSpacing.SpacingAfterOpenBrace
(is_int($functionPtr))
&& (($tokens[$functionPtr]['code'] === T_FUNCTION)
|| ($tokens[$functionPtr]['code'] === T_CLOSURE))
) {
$this->markVariableDeclaration($varName, 'param', null, $stackPtr, $functionPtr);
// Are we pass-by-reference?
$referencePtr = $phpcsFile->findPrevious(T_WHITESPACE, $stackPtr - 1, null, true, null, true);
if (($referencePtr !== false) && ($tokens[$referencePtr]['code'] === T_BITWISE_AND)) {
$varInfo = $this->getOrCreateVariableInfo($varName, $functionPtr);
$varInfo->passByReference = true;
}
// Are we optional with a default?
if (Helpers::getNextAssignPointer($phpcsFile, $stackPtr) !== null) {
$this->markVariableAssignment($varName, $stackPtr, $functionPtr);
}
return true;
}
// Is it a use keyword? Use is both a read and a define, fun!
if (($functionPtr !== false) && ($tokens[$functionPtr]['code'] === T_USE)) {
$this->markVariableRead($varName, $stackPtr, $currScope);
if ($this->isVariableUndefined($varName, $stackPtr, $currScope) === true) {
// We haven't been defined by this point.
Helpers::debug("variable $varName in function prototype looks undefined");
$phpcsFile->addWarning("Variable %s is undefined.", $stackPtr, 'UndefinedVariable', ["\${$varName}"]);
return true;
}
// $functionPtr is at the use, we need the function keyword for start of scope.
$functionPtr = $phpcsFile->findPrevious([T_CLOSURE], $functionPtr - 1, $currScope + 1, false, null, true);
if (! is_bool($functionPtr)) {
$this->markVariableDeclaration($varName, 'bound', null, $stackPtr, $functionPtr);
$this->markVariableAssignment($varName, $stackPtr, $functionPtr);
// Are we pass-by-reference?
$referencePtr = $phpcsFile->findPrevious(T_WHITESPACE, $stackPtr - 1, null, true, null, true);
if ((! is_bool($referencePtr)) && ($tokens[$referencePtr]['code'] === T_BITWISE_AND)) {
$varInfo = $this->getOrCreateVariableInfo($varName, $functionPtr);
$varInfo->passByReference = true;
}
return true;
}
}
return false;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $currScope
*
* @return bool
*/
protected function checkForClassProperty(File $phpcsFile, $stackPtr, $varName, $currScope) {
$propertyDeclarationKeywords = [
T_PUBLIC,
T_PRIVATE,
T_PROTECTED,
T_VAR,
];
$stopAtPtr = $stackPtr - 2;
$visibilityPtr = $phpcsFile->findPrevious($propertyDeclarationKeywords, $stackPtr - 1, $stopAtPtr > 0 ? $stopAtPtr : 0);
if ($visibilityPtr) {
return true;
}
$staticPtr = $phpcsFile->findPrevious(T_STATIC, $stackPtr - 1, $stopAtPtr > 0 ? $stopAtPtr : 0);
if (! $staticPtr) {
return false;
}
$stopAtPtr = $staticPtr - 2;
$visibilityPtr = $phpcsFile->findPrevious($propertyDeclarationKeywords, $staticPtr - 1, $stopAtPtr > 0 ? $stopAtPtr : 0);
if ($visibilityPtr) {
return true;
}
// it's legal to use `static` to define properties as well as to
// define variables, so make sure we are not in a function before
// assuming it's a property.
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
if ($token && !empty($token['conditions']) && !Helpers::areConditionsWithinFunctionBeforeClass($token['conditions'])) {
return Helpers::areAnyConditionsAClass($token['conditions']);
}
return false;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $currScope
*
* @return bool
*/
protected function checkForCatchBlock(File $phpcsFile, $stackPtr, $varName, $currScope) {
$tokens = $phpcsFile->getTokens();
// Are we a catch block parameter?
$openPtr = Helpers::findContainingOpeningBracket($phpcsFile, $stackPtr);
if ($openPtr === null) {
return false;
}
$catchPtr = $phpcsFile->findPrevious(T_WHITESPACE, $openPtr - 1, null, true, null, true);
if (($catchPtr !== false) && ($tokens[$catchPtr]['code'] === T_CATCH)) {
// Scope of the exception var is actually the function, not just the catch block.
$this->markVariableDeclaration($varName, 'local', null, $stackPtr, $currScope, true);
$this->markVariableAssignment($varName, $stackPtr, $currScope);
if ($this->allowUnusedCaughtExceptions) {
$varInfo = $this->getOrCreateVariableInfo($varName, $currScope);
$varInfo->ignoreUnused = true;
}
return true;
}
return false;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
*
* @return bool
*/
protected function checkForThisWithinClass(File $phpcsFile, $stackPtr, $varName) {
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
// Are we $this within a class?
if (($varName !== 'this') || empty($token['conditions'])) {
return false;
}
$inFunction = false;
foreach (array_reverse($token['conditions'], true) as $scopePtr => $scopeCode) {
// $this within a closure is valid
if ($scopeCode === T_CLOSURE && $inFunction === false) {
return true;
}
if ($scopeCode === T_CLASS || $scopeCode === T_ANON_CLASS || $scopeCode === T_TRAIT) {
return true;
}
// Handle nested function declarations.
if ($scopeCode === T_FUNCTION) {
if ($inFunction === true) {
break;
}
$inFunction = true;
}
}
return false;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
*
* @return bool
*/
protected function checkForSuperGlobal(File $phpcsFile, $stackPtr, $varName) {
// Are we a superglobal variable?
if (in_array($varName, [
'GLOBALS',
'_SERVER',
'_GET',
'_POST',
'_FILES',
'_COOKIE',
'_SESSION',
'_REQUEST',
'_ENV',
'argv',
'argc',
])) {
return true;
}
return false;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $currScope
*
* @return bool
*/
protected function checkForStaticMember(File $phpcsFile, $stackPtr, $varName, $currScope) {
$tokens = $phpcsFile->getTokens();
$doubleColonPtr = $stackPtr - 1;
if ($tokens[$doubleColonPtr]['code'] !== T_DOUBLE_COLON) {
return false;
}
$classNamePtr = $stackPtr - 2;
$staticReferences = [
T_STRING,
T_SELF,
T_PARENT,
T_STATIC,
T_VARIABLE,
];
if (! in_array($tokens[$classNamePtr]['code'], $staticReferences, true)) {
return false;
}
// "When calling static methods, the function call is stronger than the
// static property operator" so look for a function call.
$parenPointer = $phpcsFile->findNext([T_OPEN_PARENTHESIS], $stackPtr, $stackPtr + 2);
if ($parenPointer) {
return false;
}
return true;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $currScope
*
* @return bool
*/
protected function checkForStaticOutsideClass(File $phpcsFile, $stackPtr, $varName, $currScope) {
// Are we refering to self:: outside a class?
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
$doubleColonPtr = $stackPtr - 1;
if ($tokens[$doubleColonPtr]['code'] !== T_DOUBLE_COLON) {
return false;
}
$classNamePtr = $stackPtr - 2;
$code = $tokens[$classNamePtr]['code'];
$staticReferences = [
T_SELF,
T_STATIC,
];
if (! in_array($code, $staticReferences, true)) {
return false;
}
$errorClass = $code === T_SELF ? 'SelfOutsideClass' : 'StaticOutsideClass';
$staticRefType = $code === T_SELF ? 'self::' : 'static::';
if (!empty($token['conditions']) && Helpers::areAnyConditionsAClass($token['conditions'])) {
return false;
}
$phpcsFile->addError(
"Use of {$staticRefType}%s outside class definition.",
$stackPtr,
$errorClass,
["\${$varName}"]
);
return true;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $currScope
*
* @return bool
*/
protected function checkForAssignment(File $phpcsFile, $stackPtr, $varName, $currScope) {
// Is the next non-whitespace an assignment?
$assignPtr = Helpers::getNextAssignPointer($phpcsFile, $stackPtr);
if (! is_int($assignPtr)) {
return false;
}
// Is this a variable variable? If so, it's not an assignment to the current variable.
if ($this->checkForVariableVariable($phpcsFile, $stackPtr, $varName, $currScope)) {
Helpers::debug('found variable variable');
return false;
}
// Plain ol' assignment. Simpl(ish).
$writtenPtr = Helpers::findWhereAssignExecuted($phpcsFile, $assignPtr);
$this->markVariableAssignment($varName, $writtenPtr, $currScope);
// Are we are reference variable?
$tokens = $tokens = $phpcsFile->getTokens();
$referencePtr = $phpcsFile->findNext(T_WHITESPACE, $assignPtr + 1, null, true, null, true);
$varInfo = $this->getOrCreateVariableInfo($varName, $currScope);
if (($referencePtr !== false) && ($tokens[$referencePtr]['code'] === T_BITWISE_AND)) {
$varInfo->isReference = true;
} elseif ($varInfo->isReference) {
// If this is an assigment to a reference variable then that variable is
// used.
$this->markVariableRead($varName, $stackPtr, $currScope);
}
return true;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $currScope
*
* @return bool
*/
protected function checkForVariableVariable(File $phpcsFile, $stackPtr, $varName, $currScope) {
$tokens = $phpcsFile->getTokens();
if (!isset($tokens[$stackPtr - 1]['code'])) {
return false;
}
if ($tokens[$stackPtr - 1]['code'] === T_DOLLAR) {
return true;
}
if ($tokens[$stackPtr - 1]['code'] === T_OPEN_CURLY_BRACKET && isset($tokens[$stackPtr - 2]['code']) && $tokens[$stackPtr - 2]['code'] === T_DOLLAR) {
return true;
}
return false;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $currScope
*
* @return bool
*/
protected function checkForListShorthandAssignment(File $phpcsFile, $stackPtr, $varName, $currScope) {
// OK, are we within a [ ... ] construct?
$openPtr = Helpers::findContainingOpeningSquareBracket($phpcsFile, $stackPtr);
if (! is_int($openPtr)) {
return false;
}
// OK, we're a [ ... ] construct... are we being assigned to?
$closePtr = Helpers::findContainingClosingSquareBracket($phpcsFile, $stackPtr);
if (! is_int($closePtr)) {
return false;
}
$assignPtr = Helpers::getNextAssignPointer($phpcsFile, $closePtr);
if (! is_int($assignPtr)) {
return false;
}
// Yes, we're being assigned.
$writtenPtr = Helpers::findWhereAssignExecuted($phpcsFile, $assignPtr);
$this->markVariableAssignment($varName, $writtenPtr, $currScope);
return true;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $currScope
*
* @return bool
*/
protected function checkForListAssignment(File $phpcsFile, $stackPtr, $varName, $currScope) {
$tokens = $phpcsFile->getTokens();
// OK, are we within a list (...) construct?
$openPtr = Helpers::findContainingOpeningBracket($phpcsFile, $stackPtr);
if ($openPtr === null) {
return false;
}
$prevPtr = $phpcsFile->findPrevious(T_WHITESPACE, $openPtr - 1, null, true, null, true);
if (($prevPtr === false) || ($tokens[$prevPtr]['code'] !== T_LIST)) {
return false;
}
// OK, we're a list (...) construct... are we being assigned to?
$closePtr = $tokens[$openPtr]['parenthesis_closer'];
$assignPtr = Helpers::getNextAssignPointer($phpcsFile, $closePtr);
if (! is_int($assignPtr)) {
return false;
}
// Yes, we're being assigned.
$writtenPtr = Helpers::findWhereAssignExecuted($phpcsFile, $assignPtr);
$this->markVariableAssignment($varName, $writtenPtr, $currScope);
return true;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $currScope
*
* @return bool
*/
protected function checkForGlobalDeclaration(File $phpcsFile, $stackPtr, $varName, $currScope) {
$tokens = $phpcsFile->getTokens();
// Are we a global declaration?
// Search backwards for first token that isn't whitespace, comma or variable.
$globalPtr = $phpcsFile->findPrevious([T_WHITESPACE, T_VARIABLE, T_COMMA], $stackPtr - 1, null, true, null, true);
if (($globalPtr === false) || ($tokens[$globalPtr]['code'] !== T_GLOBAL)) {
return false;
}
// It's a global declaration.
$this->markVariableDeclaration($varName, 'global', null, $stackPtr, $currScope);
return true;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $currScope
*
* @return bool
*/
protected function checkForStaticDeclaration(File $phpcsFile, $stackPtr, $varName, $currScope) {
$tokens = $phpcsFile->getTokens();
// Are we a static declaration?
// Static declarations are a bit more complicated than globals, since they
// can contain assignments. The assignment is compile-time however so can
// only be constant values, which makes life manageable.
//
// Just to complicate matters further, late static binding constants
// take the form static::CONSTANT and are invalid within static variable
// assignments, but we don't want to accidentally match their use of the
// static keyword.
//
// Valid values are:
// number T_MINUS T_LNUMBER T_DNUMBER
// string T_CONSTANT_ENCAPSED_STRING
// heredoc T_START_HEREDOC T_HEREDOC T_END_HEREDOC
// nowdoc T_START_NOWDOC T_NOWDOC T_END_NOWDOC
// define T_STRING
// class constant T_STRING T_DOUBLE_COLON T_STRING
// Search backwards for first token that isn't whitespace, comma, variable,
// equals, or on the list of assignable constant values above.
$staticPtr = $phpcsFile->findPrevious(
[
T_WHITESPACE, T_VARIABLE, T_COMMA, T_EQUAL,
T_MINUS, T_LNUMBER, T_DNUMBER,
T_CONSTANT_ENCAPSED_STRING,
T_STRING,
T_DOUBLE_COLON,
T_START_HEREDOC, T_HEREDOC, T_END_HEREDOC,
T_START_NOWDOC, T_NOWDOC, T_END_NOWDOC,
],
$stackPtr - 1,
null,
true,
null,
true
);
if (($staticPtr === false) || ($tokens[$staticPtr]['code'] !== T_STATIC)) {
return false;
}
// Is it a late static binding static::?
// If so, this isn't the static keyword we're looking for, but since
// static:: isn't allowed in a compile-time constant, we also know
// we can't be part of a static declaration anyway, so there's no
// need to look any further.
$lateStaticBindingPtr = $phpcsFile->findNext(T_WHITESPACE, $staticPtr + 1, null, true, null, true);
if (($lateStaticBindingPtr !== false) && ($tokens[$lateStaticBindingPtr]['code'] === T_DOUBLE_COLON)) {
return false;
}
// It's a static declaration.
$this->markVariableDeclaration($varName, 'static', null, $stackPtr, $currScope);
if (Helpers::getNextAssignPointer($phpcsFile, $stackPtr) !== null) {
$this->markVariableAssignment($varName, $stackPtr, $currScope);
}
return true;
}
/**
* @param string $varName
*
* @return bool
*/
protected function checkForNumericVariable($varName) {
return is_numeric(substr($varName, 0, 1));
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName
* @param int $currScope
*
* @return bool
*/
protected function checkForForeachLoopVar(File $phpcsFile, $stackPtr, $varName, $currScope) {
$tokens = $phpcsFile->getTokens();
// Are we a foreach loopvar?
$openParenPtr = Helpers::findContainingOpeningBracket($phpcsFile, $stackPtr);
if (! is_int($openParenPtr)) {
return false;
}
$foreachPtr = Helpers::findParenthesisOwner($phpcsFile, $openParenPtr);
if (! is_int($foreachPtr)) {
return false;
}
if ($tokens[$foreachPtr]['code'] === T_LIST) {
$openParenPtr = Helpers::findContainingOpeningBracket($phpcsFile, $foreachPtr);
if (! is_int($openParenPtr)) {
return false;
}
$foreachPtr = Helpers::findParenthesisOwner($phpcsFile, $openParenPtr);
if (! is_int($foreachPtr)) {
return false;
}
}
if ($tokens[$foreachPtr]['code'] !== T_FOREACH) {
return false;
}
// Is there an 'as' token between us and the foreach?
if ($phpcsFile->findPrevious(T_AS, $stackPtr - 1, $openParenPtr) === false) {
return false;