-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathHelpers.php
1781 lines (1647 loc) · 51.1 KB
/
Helpers.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
namespace VariableAnalysis\Lib;
use PHP_CodeSniffer\Files\File;
use VariableAnalysis\Lib\ScopeInfo;
use VariableAnalysis\Lib\Constants;
use VariableAnalysis\Lib\ForLoopInfo;
use VariableAnalysis\Lib\EnumInfo;
use VariableAnalysis\Lib\ScopeType;
use VariableAnalysis\Lib\VariableInfo;
use PHP_CodeSniffer\Util\Tokens;
class Helpers
{
/**
* @return array<int|string>
*/
public static function getPossibleEndOfFileTokens()
{
return array_merge(
array_values(Tokens::$emptyTokens),
[
T_INLINE_HTML,
T_CLOSE_TAG,
]
);
}
/**
* @param int|bool $value
*
* @return ?int
*/
public static function getIntOrNull($value)
{
return is_int($value) ? $value : null;
}
/**
* Find the position of the square bracket containing the token at $stackPtr,
* if any.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return ?int
*/
public static function findContainingOpeningSquareBracket(File $phpcsFile, $stackPtr)
{
// Find the previous bracket within this same statement.
$previousStatementPtr = self::getPreviousStatementPtr($phpcsFile, $stackPtr);
$openBracketPosition = self::getIntOrNull($phpcsFile->findPrevious([T_OPEN_SHORT_ARRAY, T_OPEN_SQUARE_BRACKET], $stackPtr - 1, $previousStatementPtr));
if (empty($openBracketPosition)) {
return null;
}
// Make sure we are inside the pair of brackets we found.
$tokens = $phpcsFile->getTokens();
$openBracketToken = $tokens[$openBracketPosition];
if (empty($openBracketToken) || empty($tokens[$openBracketToken['bracket_closer']])) {
return null;
}
$closeBracketPosition = $openBracketToken['bracket_closer'];
if (empty($closeBracketPosition)) {
return null;
}
if ($stackPtr > $closeBracketPosition) {
return null;
}
return $openBracketPosition;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
*
* @return int
*/
public static function getPreviousStatementPtr(File $phpcsFile, $stackPtr)
{
$result = $phpcsFile->findPrevious([T_SEMICOLON, T_CLOSE_CURLY_BRACKET], $stackPtr - 1);
return is_bool($result) ? 1 : $result;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
*
* @return ?int
*/
public static function findContainingOpeningBracket(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if (isset($tokens[$stackPtr]['nested_parenthesis'])) {
/**
* @var array<int|string|null>
*/
$openPtrs = array_keys($tokens[$stackPtr]['nested_parenthesis']);
return (int)end($openPtrs);
}
return null;
}
/**
* @param array{conditions: (int|string)[], content: string} $token
*
* @return bool
*/
public static function areAnyConditionsAClass(array $token)
{
$conditions = $token['conditions'];
$classlikeCodes = [T_CLASS, T_ANON_CLASS, T_TRAIT];
if (defined('T_ENUM')) {
$classlikeCodes[] = T_ENUM;
}
$classlikeCodes[] = 'PHPCS_T_ENUM';
foreach (array_reverse($conditions, true) as $scopeCode) {
if (in_array($scopeCode, $classlikeCodes, true)) {
return true;
}
}
return false;
}
/**
* Return true if the token conditions are within a function before they are
* within a class.
*
* @param array{conditions: (int|string)[], content: string} $token
*
* @return bool
*/
public static function areConditionsWithinFunctionBeforeClass(array $token)
{
$conditions = $token['conditions'];
$classlikeCodes = [T_CLASS, T_ANON_CLASS, T_TRAIT];
if (defined('T_ENUM')) {
$classlikeCodes[] = T_ENUM;
}
$classlikeCodes[] = 'PHPCS_T_ENUM';
foreach (array_reverse($conditions, true) as $scopeCode) {
if (in_array($scopeCode, $classlikeCodes)) {
return false;
}
if ($scopeCode === T_FUNCTION) {
return true;
}
}
return false;
}
/**
* Return true if the token conditions are within an IF/ELSE/ELSEIF block
* before they are within a class or function.
*
* @param (int|string)[] $conditions
*
* @return int|string|null
*/
public static function getClosestConditionPositionIfBeforeOtherConditions(array $conditions)
{
$conditionsInsideOut = array_reverse($conditions, true);
if (empty($conditions)) {
return null;
}
$scopeCode = reset($conditionsInsideOut);
$conditionalCodes = [
T_IF,
T_ELSE,
T_ELSEIF,
];
if (in_array($scopeCode, $conditionalCodes, true)) {
return key($conditionsInsideOut);
}
return null;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
*
* @return bool
*/
public static function isTokenFunctionParameter(File $phpcsFile, $stackPtr)
{
return is_int(self::getFunctionIndexForFunctionParameter($phpcsFile, $stackPtr));
}
/**
* Return true if the token is inside the arguments of a function call.
*
* For example, the variable `$foo` in `doSomething($foo)` is inside the
* arguments to the call to `doSomething()`.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return bool
*/
public static function isTokenInsideFunctionCallArgument(File $phpcsFile, $stackPtr)
{
return is_int(self::getFunctionIndexForFunctionCallArgument($phpcsFile, $stackPtr));
}
/**
* Find the index of the function keyword for a token in a function
* definition's parameters.
*
* Does not work for tokens inside the "use".
*
* Will also work for the parenthesis that make up the function definition's
* parameters list.
*
* For arguments inside a function call, rather than a definition, use
* `getFunctionIndexForFunctionCallArgument`.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return ?int
*/
public static function getFunctionIndexForFunctionParameter(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
if ($token['code'] === 'PHPCS_T_OPEN_PARENTHESIS') {
$startOfArguments = $stackPtr;
} elseif ($token['code'] === 'PHPCS_T_CLOSE_PARENTHESIS') {
if (empty($token['parenthesis_opener'])) {
return null;
}
$startOfArguments = $token['parenthesis_opener'];
} else {
if (empty($token['nested_parenthesis'])) {
return null;
}
$startingParenthesis = array_keys($token['nested_parenthesis']);
$startOfArguments = end($startingParenthesis);
}
if (! is_int($startOfArguments)) {
return null;
}
$nonFunctionTokenTypes = Tokens::$emptyTokens;
$nonFunctionTokenTypes[] = T_STRING;
$nonFunctionTokenTypes[] = T_BITWISE_AND;
$functionPtr = self::getIntOrNull($phpcsFile->findPrevious($nonFunctionTokenTypes, $startOfArguments - 1, null, true, null, true));
if (! is_int($functionPtr)) {
return null;
}
$functionToken = $tokens[$functionPtr];
$functionTokenTypes = [
T_FUNCTION,
T_CLOSURE,
];
if (!in_array($functionToken['code'], $functionTokenTypes, true) && ! self::isArrowFunction($phpcsFile, $functionPtr)) {
return null;
}
return $functionPtr;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
*
* @return bool
*/
public static function isTokenInsideFunctionUseImport(File $phpcsFile, $stackPtr)
{
return is_int(self::getUseIndexForUseImport($phpcsFile, $stackPtr));
}
/**
* Find the token index of the "use" for a token inside a function use import
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return ?int
*/
public static function getUseIndexForUseImport(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$nonUseTokenTypes = Tokens::$emptyTokens;
$nonUseTokenTypes[] = T_VARIABLE;
$nonUseTokenTypes[] = T_ELLIPSIS;
$nonUseTokenTypes[] = T_COMMA;
$nonUseTokenTypes[] = T_BITWISE_AND;
$openParenPtr = self::getIntOrNull($phpcsFile->findPrevious($nonUseTokenTypes, $stackPtr - 1, null, true, null, true));
if (! is_int($openParenPtr) || $tokens[$openParenPtr]['code'] !== T_OPEN_PARENTHESIS) {
return null;
}
$usePtr = self::getIntOrNull($phpcsFile->findPrevious(array_values($nonUseTokenTypes), $openParenPtr - 1, null, true, null, true));
if (! is_int($usePtr) || $tokens[$usePtr]['code'] !== T_USE) {
return null;
}
return $usePtr;
}
/**
* Return the index of a function's name token from inside the function.
*
* $stackPtr must be inside the function body or parameters for this to work.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return ?int
*/
public static function findFunctionCall(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$openPtr = self::findContainingOpeningBracket($phpcsFile, $stackPtr);
if (is_int($openPtr)) {
// First non-whitespace thing and see if it's a T_STRING function name
$functionPtr = $phpcsFile->findPrevious(Tokens::$emptyTokens, $openPtr - 1, null, true, null, true);
if (is_int($functionPtr) && $tokens[$functionPtr]['code'] === T_STRING) {
return $functionPtr;
}
}
return null;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
*
* @return array<int, array<int>>
*/
public static function findFunctionCallArguments(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Slight hack: also allow this to find args for array constructor.
if (($tokens[$stackPtr]['code'] !== T_STRING) && ($tokens[$stackPtr]['code'] !== T_ARRAY)) {
// Assume $stackPtr is something within the brackets, find our function call
$stackPtr = self::findFunctionCall($phpcsFile, $stackPtr);
if ($stackPtr === null) {
return [];
}
}
// $stackPtr is the function name, find our brackets after it
$openPtr = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
if (($openPtr === false) || ($tokens[$openPtr]['code'] !== T_OPEN_PARENTHESIS)) {
return [];
}
if (!isset($tokens[$openPtr]['parenthesis_closer'])) {
return [];
}
$closePtr = $tokens[$openPtr]['parenthesis_closer'];
$argPtrs = [];
$lastPtr = $openPtr;
$lastArgComma = $openPtr;
$nextPtr = $phpcsFile->findNext([T_COMMA], $lastPtr + 1, $closePtr);
while (is_int($nextPtr)) {
if (self::findContainingOpeningBracket($phpcsFile, $nextPtr) === $openPtr) {
// Comma is at our level of brackets, it's an argument delimiter.
$range = range($lastArgComma + 1, $nextPtr - 1);
$range = array_filter($range, function ($element) {
return is_int($element);
});
array_push($argPtrs, $range);
$lastArgComma = $nextPtr;
}
$lastPtr = $nextPtr;
$nextPtr = $phpcsFile->findNext([T_COMMA], $lastPtr + 1, $closePtr);
}
$range = range($lastArgComma + 1, $closePtr - 1);
$range = array_filter($range, function ($element) {
return is_int($element);
});
array_push($argPtrs, $range);
return $argPtrs;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
*
* @return ?int
*/
public static function getNextAssignPointer(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
// Is the next non-whitespace an assignment?
$nextPtr = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
if (is_int($nextPtr)
&& isset(Tokens::$assignmentTokens[$tokens[$nextPtr]['code']])
// Ignore double arrow to prevent triggering on `foreach ( $array as $k => $v )`.
&& $tokens[$nextPtr]['code'] !== T_DOUBLE_ARROW
) {
return $nextPtr;
}
return null;
}
/**
* @param string $varName
*
* @return string
*/
public static function normalizeVarName($varName)
{
$result = preg_replace('/[{}$]/', '', $varName);
return $result ? $result : $varName;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param string $varName (optional) if it differs from the normalized 'content' of the token at $stackPtr
*
* @return ?int
*/
public static function findVariableScope(File $phpcsFile, $stackPtr, $varName = null)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
$varName = isset($varName) ? $varName : self::normalizeVarName($token['content']);
$enclosingScopeIndex = self::findVariableScopeExceptArrowFunctions($phpcsFile, $stackPtr);
if (!is_null($enclosingScopeIndex)) {
$arrowFunctionIndex = self::getContainingArrowFunctionIndex($phpcsFile, $stackPtr, $enclosingScopeIndex);
$isTokenInsideArrowFunctionBody = is_int($arrowFunctionIndex);
if ($isTokenInsideArrowFunctionBody) {
// Get the list of variables defined by the arrow function
// If this matches any of them, the scope is the arrow function,
// otherwise, it uses the enclosing scope.
if ($arrowFunctionIndex) {
$variableNames = self::getVariablesDefinedByArrowFunction($phpcsFile, $arrowFunctionIndex);
self::debug('findVariableScope: looking for', $varName, 'in arrow function variables', $variableNames);
if (in_array($varName, $variableNames, true)) {
return $arrowFunctionIndex;
}
}
}
}
return $enclosingScopeIndex;
}
/**
* Return the variable names and positions of each variable targetted by a `compact()` call.
*
* @param File $phpcsFile
* @param int $stackPtr
* @param array<int, array<int>> $arguments The stack pointers of each argument; see findFunctionCallArguments
*
* @return array<VariableInfo> each variable's firstRead position and its name; other VariableInfo properties are not set!
*/
public static function getVariablesInsideCompact(File $phpcsFile, $stackPtr, $arguments)
{
$tokens = $phpcsFile->getTokens();
$variablePositionsAndNames = [];
foreach ($arguments as $argumentPtrs) {
$argumentPtrs = array_values(array_filter($argumentPtrs, function ($argumentPtr) use ($tokens) {
return isset(Tokens::$emptyTokens[$tokens[$argumentPtr]['code']]) === false;
}));
if (empty($argumentPtrs)) {
continue;
}
if (!isset($tokens[$argumentPtrs[0]])) {
continue;
}
$argumentFirstToken = $tokens[$argumentPtrs[0]];
if ($argumentFirstToken['code'] === T_ARRAY) {
// It's an array argument, recurse.
$arrayArguments = self::findFunctionCallArguments($phpcsFile, $argumentPtrs[0]);
$variablePositionsAndNames = array_merge($variablePositionsAndNames, self::getVariablesInsideCompact($phpcsFile, $stackPtr, $arrayArguments));
continue;
}
if (count($argumentPtrs) > 1) {
// Complex argument, we can't handle it, ignore.
continue;
}
if ($argumentFirstToken['code'] === T_CONSTANT_ENCAPSED_STRING) {
// Single-quoted string literal, ie compact('whatever').
// Substr is to strip the enclosing single-quotes.
$varName = substr($argumentFirstToken['content'], 1, -1);
$variable = new VariableInfo($varName);
$variable->firstRead = $argumentPtrs[0];
$variablePositionsAndNames[] = $variable;
continue;
}
if ($argumentFirstToken['code'] === T_DOUBLE_QUOTED_STRING) {
// Double-quoted string literal.
$regexp = Constants::getDoubleQuotedVarRegexp();
if (! empty($regexp) && preg_match($regexp, $argumentFirstToken['content'])) {
// Bail if the string needs variable expansion, that's runtime stuff.
continue;
}
// Substr is to strip the enclosing double-quotes.
$varName = substr($argumentFirstToken['content'], 1, -1);
$variable = new VariableInfo($varName);
$variable->firstRead = $argumentPtrs[0];
$variablePositionsAndNames[] = $variable;
continue;
}
}
return $variablePositionsAndNames;
}
/**
* Return the token index of the scope start for a token
*
* For a variable within a function body, or a variable within a function
* definition argument list, this will return the function keyword's index.
*
* For a variable within a "use" import list within a function definition,
* this will return the enclosing scope, not the function keyword. This is
* important to note because the "use" keyword performs double-duty, defining
* variables for the function's scope, and consuming the variables in the
* enclosing scope. Use `getUseIndexForUseImport` to determine if this
* token needs to be treated as a "use".
*
* For a variable within an arrow function definition argument list,
* this will return the arrow function's keyword index.
*
* For a variable in an arrow function body, this will return the enclosing
* function's index, which may be incorrect.
*
* Since a variable in an arrow function's body may be imported from the
* enclosing scope, it's important to test to see if the variable is in an
* arrow function and also check its enclosing scope separately.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return ?int
*/
public static function findVariableScopeExceptArrowFunctions(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$allowedTypes = [
T_VARIABLE,
T_DOUBLE_QUOTED_STRING,
T_HEREDOC,
T_STRING,
];
if (! in_array($tokens[$stackPtr]['code'], $allowedTypes, true)) {
throw new \Exception("Cannot find variable scope for non-variable {$tokens[$stackPtr]['type']}");
}
$startOfTokenScope = self::getStartOfTokenScope($phpcsFile, $stackPtr);
if (is_int($startOfTokenScope) && $startOfTokenScope > 0) {
return $startOfTokenScope;
}
// If there is no "conditions" array, this is a function definition argument.
if (self::isTokenFunctionParameter($phpcsFile, $stackPtr)) {
$functionPtr = self::getFunctionIndexForFunctionParameter($phpcsFile, $stackPtr);
if (! is_int($functionPtr)) {
throw new \Exception("Function index not found for function argument index {$stackPtr}");
}
return $functionPtr;
}
self::debug('Cannot find function scope for variable at', $stackPtr);
return $startOfTokenScope;
}
/**
* Return the token index of the scope start for a variable token
*
* This will only work for a variable within a function's body. Otherwise,
* see `findVariableScope`, which is more complex.
*
* Note that if used on a variable in an arrow function, it will return the
* enclosing function's scope, which may be incorrect.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return ?int
*/
private static function getStartOfTokenScope(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
$inClass = false;
$conditions = isset($token['conditions']) ? $token['conditions'] : [];
$functionTokenTypes = [
T_FUNCTION,
T_CLOSURE,
];
foreach (array_reverse($conditions, true) as $scopePtr => $scopeCode) {
if (in_array($scopeCode, $functionTokenTypes, true) || self::isArrowFunction($phpcsFile, $scopePtr)) {
return $scopePtr;
}
if (isset(Tokens::$ooScopeTokens[$scopeCode]) === true) {
$inClass = true;
}
}
if ($inClass) {
// If this is inside a class and not inside a function, this is either a
// class member variable definition, or a function argument. If it is a
// variable definition, it has no scope on its own (it can only be used
// with an object reference). If it is a function argument, we need to do
// more work (see `findVariableScopeExceptArrowFunctions`).
return null;
}
// If we can't find a scope, let's use the first token of the file.
return 0;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
*
* @return bool
*/
public static function isTokenInsideArrowFunctionDefinition(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
$openParenIndices = isset($token['nested_parenthesis']) ? $token['nested_parenthesis'] : [];
if (empty($openParenIndices)) {
return false;
}
$openParenPtr = $openParenIndices[0];
return self::isArrowFunction($phpcsFile, $openParenPtr - 1);
}
/**
* @param File $phpcsFile
* @param int $stackPtr
* @param int $enclosingScopeIndex
*
* @return ?int
*/
public static function getContainingArrowFunctionIndex(File $phpcsFile, $stackPtr, $enclosingScopeIndex)
{
$arrowFunctionIndex = self::getPreviousArrowFunctionIndex($phpcsFile, $stackPtr, $enclosingScopeIndex);
if (! is_int($arrowFunctionIndex)) {
return null;
}
$arrowFunctionInfo = self::getArrowFunctionOpenClose($phpcsFile, $arrowFunctionIndex);
if (! $arrowFunctionInfo) {
return null;
}
// We found the closest arrow function before this token. If the token is
// within the scope of that arrow function, then return it.
if ($stackPtr > $arrowFunctionInfo['scope_opener'] && $stackPtr < $arrowFunctionInfo['scope_closer']) {
return $arrowFunctionIndex;
}
// If the token is after the scope of the closest arrow function, we may
// still be inside the scope of a nested arrow function, so we need to
// search further back until we are certain there are no more arrow
// functions.
if ($stackPtr > $arrowFunctionInfo['scope_closer']) {
return self::getContainingArrowFunctionIndex($phpcsFile, $arrowFunctionIndex, $enclosingScopeIndex);
}
return null;
}
/**
* Move back from the stackPtr to the start of the enclosing scope until we
* find a 'fn' token that starts an arrow function, returning the index of
* that token. Returns null if there are no arrow functions before stackPtr.
*
* Note that this does not guarantee that stackPtr is inside the arrow
* function scope we find!
*
* @param File $phpcsFile
* @param int $stackPtr
* @param int $enclosingScopeIndex
*
* @return ?int
*/
private static function getPreviousArrowFunctionIndex(File $phpcsFile, $stackPtr, $enclosingScopeIndex)
{
$tokens = $phpcsFile->getTokens();
for ($index = $stackPtr - 1; $index > $enclosingScopeIndex; $index--) {
$token = $tokens[$index];
if ($token['content'] === 'fn' && self::isArrowFunction($phpcsFile, $index)) {
return $index;
}
}
return null;
}
/**
* @param File $phpcsFile
* @param int $stackPtr
*
* @return bool
*/
public static function isArrowFunction(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if (defined('T_FN') && $tokens[$stackPtr]['code'] === T_FN) {
return true;
}
if ($tokens[$stackPtr]['content'] !== 'fn') {
return false;
}
// Make sure next non-space token is an open parenthesis
$openParenIndex = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, true);
if (! is_int($openParenIndex) || $tokens[$openParenIndex]['code'] !== T_OPEN_PARENTHESIS) {
return false;
}
// Find the associated close parenthesis
$closeParenIndex = $tokens[$openParenIndex]['parenthesis_closer'];
// Make sure the next token is a fat arrow
$fatArrowIndex = $phpcsFile->findNext(Tokens::$emptyTokens, $closeParenIndex + 1, null, true);
if (! is_int($fatArrowIndex)) {
return false;
}
if ($tokens[$fatArrowIndex]['code'] !== T_DOUBLE_ARROW && $tokens[$fatArrowIndex]['type'] !== 'T_FN_ARROW') {
return false;
}
return true;
}
/**
* Find the opening and closing scope positions for an arrow function if the
* given position is the start of the arrow function (the `fn` keyword
* token).
*
* Returns null if the passed token is not an arrow function keyword.
*
* If the token is an arrow function keyword, the scope opener is returned as
* the provided position.
*
* @param File $phpcsFile
* @param int $stackPtr
*
* @return ?array<string, int>
*/
public static function getArrowFunctionOpenClose(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$stackPtr]['content'] !== 'fn') {
return null;
}
// Make sure next non-space token is an open parenthesis
$openParenIndex = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, true);
if (! is_int($openParenIndex) || $tokens[$openParenIndex]['code'] !== T_OPEN_PARENTHESIS) {
return null;
}
// Find the associated close parenthesis
$closeParenIndex = $tokens[$openParenIndex]['parenthesis_closer'];
// Make sure the next token is a fat arrow or a return type
$fatArrowIndex = $phpcsFile->findNext(Tokens::$emptyTokens, $closeParenIndex + 1, null, true);
if (! is_int($fatArrowIndex)) {
return null;
}
if (
$tokens[$fatArrowIndex]['code'] !== T_DOUBLE_ARROW &&
$tokens[$fatArrowIndex]['type'] !== 'T_FN_ARROW' &&
$tokens[$fatArrowIndex]['code'] !== T_COLON
) {
return null;
}
// Find the scope closer
$scopeCloserIndex = null;
$foundCurlyPairs = 0;
$foundArrayPairs = 0;
$foundParenPairs = 0;
$arrowBodyStart = $tokens[$stackPtr]['parenthesis_closer'] + 1;
$lastToken = self::getLastNonEmptyTokenIndexInFile($phpcsFile);
for ($index = $arrowBodyStart; $index < $lastToken; $index++) {
$token = $tokens[$index];
if (empty($token['code'])) {
$scopeCloserIndex = $index;
break;
}
$code = $token['code'];
// A semicolon is always a closer.
if ($code === T_SEMICOLON) {
$scopeCloserIndex = $index;
break;
}
// Track pair opening tokens.
if ($code === T_OPEN_CURLY_BRACKET) {
$foundCurlyPairs += 1;
continue;
}
if ($code === T_OPEN_SHORT_ARRAY || $code === T_OPEN_SQUARE_BRACKET) {
$foundArrayPairs += 1;
continue;
}
if ($code === T_OPEN_PARENTHESIS) {
$foundParenPairs += 1;
continue;
}
// A pair closing is only an arrow func closer if there was no matching opening token.
if ($code === T_CLOSE_CURLY_BRACKET) {
if ($foundCurlyPairs === 0) {
$scopeCloserIndex = $index;
break;
}
$foundCurlyPairs -= 1;
continue;
}
if ($code === T_CLOSE_SHORT_ARRAY || $code === T_CLOSE_SQUARE_BRACKET) {
if ($foundArrayPairs === 0) {
$scopeCloserIndex = $index;
break;
}
$foundArrayPairs -= 1;
continue;
}
if ($code === T_CLOSE_PARENTHESIS) {
if ($foundParenPairs === 0) {
$scopeCloserIndex = $index;
break;
}
$foundParenPairs -= 1;
continue;
}
// A comma is a closer only if we are not inside an opening token.
if ($code === T_COMMA) {
if (empty($foundArrayPairs) && empty($foundParenPairs) && empty($foundCurlyPairs)) {
$scopeCloserIndex = $index;
break;
}
continue;
}
}
if (! is_int($scopeCloserIndex)) {
return null;
}
return [
'scope_opener' => $stackPtr,
'scope_closer' => $scopeCloserIndex,
];
}
/**
* Determine if a token is a list opener for list assignment/destructuring.
*
* The index provided can be either the opening square brace of a short list
* assignment like the first character of `[$a] = $b;` or the `list` token of
* an expression like `list($a) = $b;` or the opening parenthesis of that
* expression.
*
* @param File $phpcsFile
* @param int $listOpenerIndex
*
* @return bool
*/
private static function isListAssignment(File $phpcsFile, $listOpenerIndex)
{
$tokens = $phpcsFile->getTokens();
// Match `[$a] = $b;` except for when the previous token is a parenthesis.
if ($tokens[$listOpenerIndex]['code'] === T_OPEN_SHORT_ARRAY) {
return true;
}
// Match `list($a) = $b;`
if ($tokens[$listOpenerIndex]['code'] === T_LIST) {
return true;
}
// If $listOpenerIndex is the open parenthesis of `list($a) = $b;`, then
// match that too.
if ($tokens[$listOpenerIndex]['code'] === T_OPEN_PARENTHESIS) {
$previousTokenPtr = $phpcsFile->findPrevious(Tokens::$emptyTokens, $listOpenerIndex - 1, null, true);
if (
isset($tokens[$previousTokenPtr])
&& $tokens[$previousTokenPtr]['code'] === T_LIST
) {
return true;
}
return true;
}
// If the list opener token is a square bracket that is preceeded by a
// close parenthesis that has an owner which is a scope opener, then this
// is a list assignment and not an array access.
//
// Match `if (true) [$a] = $b;`
if ($tokens[$listOpenerIndex]['code'] === T_OPEN_SQUARE_BRACKET) {
$previousTokenPtr = $phpcsFile->findPrevious(Tokens::$emptyTokens, $listOpenerIndex - 1, null, true);
if (
isset($tokens[$previousTokenPtr])
&& $tokens[$previousTokenPtr]['code'] === T_CLOSE_PARENTHESIS
&& isset($tokens[$previousTokenPtr]['parenthesis_owner'])
&& isset(Tokens::$scopeOpeners[$tokens[$tokens[$previousTokenPtr]['parenthesis_owner']]['code']])
) {
return true;
}
}
return false;
}
/**
* Return a list of indices for variables assigned within a list assignment.
*
* The index provided can be either the opening square brace of a short list
* assignment like the first character of `[$a] = $b;` or the `list` token of
* an expression like `list($a) = $b;` or the opening parenthesis of that
* expression.
*
* @param File $phpcsFile
* @param int $listOpenerIndex
*
* @return ?array<int>
*/
public static function getListAssignments(File $phpcsFile, $listOpenerIndex)
{
$tokens = $phpcsFile->getTokens();
self::debug('getListAssignments', $listOpenerIndex, $tokens[$listOpenerIndex]);
// First find the end of the list
$closePtr = null;
if (isset($tokens[$listOpenerIndex]['parenthesis_closer'])) {
$closePtr = $tokens[$listOpenerIndex]['parenthesis_closer'];
}
if (isset($tokens[$listOpenerIndex]['bracket_closer'])) {
$closePtr = $tokens[$listOpenerIndex]['bracket_closer'];
}
if (! $closePtr) {
return null;
}
// Find the assignment (equals sign) which, if this is a list assignment, should be the next non-space token
$assignPtr = $phpcsFile->findNext(Tokens::$emptyTokens, $closePtr + 1, null, true);
// If the next token isn't an assignment, check for nested brackets because we might be a nested assignment
if (! is_int($assignPtr) || $tokens[$assignPtr]['code'] !== T_EQUAL) {
// Collect the enclosing list open/close tokens ($parents is an assoc array keyed by opener index and the value is the closer index)
$parents = isset($tokens[$listOpenerIndex]['nested_parenthesis']) ? $tokens[$listOpenerIndex]['nested_parenthesis'] : [];
// There's no record of nested brackets for short lists; we'll have to find the parent ourselves
if (empty($parents)) {
$parentSquareBracketPtr = self::findContainingOpeningSquareBracket($phpcsFile, $listOpenerIndex);
if (is_int($parentSquareBracketPtr)) {
// Make sure that the parent is really a parent by checking that its
// closing index is outside of the current bracket's closing index.
$parentSquareBracketToken = $tokens[$parentSquareBracketPtr];
$parentSquareBracketClosePtr = $parentSquareBracketToken['bracket_closer'];
if ($parentSquareBracketClosePtr && $parentSquareBracketClosePtr > $closePtr) {
self::debug("found enclosing bracket for {$listOpenerIndex}: {$parentSquareBracketPtr}");
// Collect the opening index, but we don't actually need the closing paren index so just make that 0
$parents = [$parentSquareBracketPtr => 0];
}
}
}
// If we have no parents, this is not a nested assignment and therefore is not an assignment
if (empty($parents)) {
return null;
}
// Recursively check to see if the parent is a list assignment (we only need to check one level due to the recursion)
$isNestedAssignment = null;
$parentListOpener = array_keys(array_reverse($parents, true))[0];
$isNestedAssignment = self::getListAssignments($phpcsFile, $parentListOpener);
if ($isNestedAssignment === null) {
return null;
}
}
$variablePtrs = [];
$currentPtr = $listOpenerIndex;
$variablePtr = 0;
while ($currentPtr < $closePtr && is_int($variablePtr)) {
$variablePtr = $phpcsFile->findNext([T_VARIABLE], $currentPtr + 1, $closePtr);
if (is_int($variablePtr)) {
$variablePtrs[] = $variablePtr;
}
++$currentPtr;
}
if (! self::isListAssignment($phpcsFile, $listOpenerIndex)) {
return null;
}
return $variablePtrs;
}
/**
* @param File $phpcsFile