-
-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathPhpElementsUtil.java
2171 lines (1828 loc) · 83 KB
/
PhpElementsUtil.java
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
package fr.adrienbrault.idea.symfony2plugin.util;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.patterns.ElementPattern;
import com.intellij.patterns.PatternCondition;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.patterns.PsiElementPattern;
import com.intellij.psi.*;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.ProcessingContext;
import com.intellij.util.Processor;
import com.jetbrains.php.PhpClassHierarchyUtils;
import com.jetbrains.php.PhpIndex;
import com.jetbrains.php.codeInsight.PhpCodeInsightUtil;
import com.jetbrains.php.codeInsight.PhpScopeHolder;
import com.jetbrains.php.codeInsight.controlFlow.PhpControlFlowUtil;
import com.jetbrains.php.codeInsight.controlFlow.PhpInstructionProcessor;
import com.jetbrains.php.codeInsight.controlFlow.instructions.PhpAccessVariableInstruction;
import com.jetbrains.php.codeInsight.controlFlow.instructions.PhpCallInstruction;
import com.jetbrains.php.codeInsight.controlFlow.instructions.PhpConstructorCallInstruction;
import com.jetbrains.php.codeInsight.controlFlow.instructions.PhpReturnInstruction;
import com.jetbrains.php.completion.PhpLookupElement;
import com.jetbrains.php.lang.PhpLangUtil;
import com.jetbrains.php.lang.PhpLanguage;
import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;
import com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag;
import com.jetbrains.php.lang.lexer.PhpTokenTypes;
import com.jetbrains.php.lang.parser.PhpElementTypes;
import com.jetbrains.php.lang.patterns.PhpPatterns;
import com.jetbrains.php.lang.psi.PhpFile;
import com.jetbrains.php.lang.psi.PhpPsiElementFactory;
import com.jetbrains.php.lang.psi.PhpPsiUtil;
import com.jetbrains.php.lang.psi.elements.*;
import com.jetbrains.php.lang.psi.elements.impl.ClassConstImpl;
import com.jetbrains.php.lang.psi.elements.impl.ConstantImpl;
import com.jetbrains.php.lang.psi.elements.impl.PhpDefineImpl;
import com.jetbrains.php.lang.psi.resolve.types.PhpType;
import com.jetbrains.php.lang.psi.stubs.indexes.expectedArguments.PhpExpectedFunctionArgument;
import com.jetbrains.php.lang.psi.stubs.indexes.expectedArguments.PhpExpectedFunctionClassConstantArgument;
import com.jetbrains.php.lang.psi.stubs.indexes.expectedArguments.PhpExpectedFunctionScalarArgument;
import com.jetbrains.php.phpunit.PhpUnitUtil;
import com.jetbrains.php.refactoring.PhpAliasImporter;
import fr.adrienbrault.idea.symfony2plugin.dic.MethodReferenceBag;
import fr.adrienbrault.idea.symfony2plugin.util.psi.PsiElementAssertUtil;
import kotlin.Pair;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class PhpElementsUtil {
/**
* Only parameter on first index or named: "a('caret'), a(test: 'caret')"
*/
private static final PatternCondition<StringLiteralExpression> WITH_PREVIOUS_WHITESPACE_OR_COLON = new PatternCondition<>("whitespace or colon") {
@Override
public boolean accepts(@NotNull StringLiteralExpression element, ProcessingContext context) {
ASTNode previousNonWhitespaceSibling = FormatterUtil.getPreviousNonWhitespaceSibling(element.getNode());
return previousNonWhitespaceSibling == null || previousNonWhitespaceSibling.getElementType() == PhpTokenTypes.opCOLON;
}
};
/**
* Gets all array keys as string of an ArrayCreationExpression
*
* ['foo' => $bar]
*/
@NotNull
static public Collection<String> getArrayCreationKeys(@NotNull ArrayCreationExpression arrayCreationExpression) {
return getArrayCreationKeyMap(arrayCreationExpression).keySet();
}
/**
* Gets array key-value as single PsiElement map
*
* ['foo' => $bar]
*/
@NotNull
static public Map<String, PsiElement> getArrayCreationKeyMap(@NotNull ArrayCreationExpression arrayCreationExpression) {
Map<String, PsiElement> keys = new HashMap<>();
for(ArrayHashElement arrayHashElement: arrayCreationExpression.getHashElements()) {
PhpPsiElement child = arrayHashElement.getKey();
if(child instanceof StringLiteralExpression) {
keys.put(((StringLiteralExpression) child).getContents(), child);
}
if(child instanceof ClassConstantReference) {
PsiElement val = ((ClassConstantReference) child).resolve();
if (val instanceof ClassConstImpl) {
PsiElement value = ((ClassConstImpl) val).getDefaultValue();
if (value != null && value.getText() != null) {
keys.put(value.getText().replace("\"", "").replace("\'", ""), child);
}
}
}
if(child instanceof ConstantReference) {
PsiElement val = ((ConstantReference) child).resolve();
if(val instanceof PhpDefine) {
PhpPsiElement value = ((PhpDefineImpl) val).getValue();
if (value != null) {
keys.put(value.getText().replace("\"", "").replace("\'", ""), child);
}
}
if(val instanceof ConstantImpl) {
PsiElement value = ((ConstantImpl) val).getValue();
if (value != null && value.getText() != null) {
keys.put(value.getText().replace("\"", "").replace("\'", ""), child);
}
}
}
}
return keys;
}
/**
* Gets string values of array
*
* ["value", "value2"]
*/
@NotNull
static public Set<String> getArrayValuesAsString(@NotNull ArrayCreationExpression arrayCreationExpression) {
return getArrayValuesAsMap(arrayCreationExpression).keySet();
}
/**
* Get array string values mapped with their PsiElements
*
* ["value", "value2"]
*/
@NotNull
static public Map<String, PsiElement> getArrayValuesAsMap(@NotNull ArrayCreationExpression arrayCreationExpression) {
Collection<PsiElement> arrayValues = PhpPsiUtil.getChildren(arrayCreationExpression, psiElement ->
psiElement.getNode().getElementType() == PhpElementTypes.ARRAY_VALUE
);
Map<String, PsiElement> keys = new HashMap<>();
for (PsiElement child : arrayValues) {
String stringValue = PhpElementsUtil.getStringValue(child.getFirstChild());
if(StringUtils.isNotBlank(stringValue)) {
keys.put(stringValue, child);
}
}
return keys;
}
/**
* Get array values
*
* ["value", FOO::class] but not [$foo . $foo, $foo]
*/
@NotNull
static public PsiElement[] getArrayValues(@NotNull ArrayCreationExpression arrayCreationExpression) {
Collection<PsiElement> arrayValues = PhpPsiUtil.getChildren(arrayCreationExpression, psiElement ->
psiElement.getNode().getElementType() == PhpElementTypes.ARRAY_VALUE
);
List<PsiElement> items = new ArrayList<>();
for (PsiElement child : arrayValues) {
if (child instanceof PhpPsiElement) {
PsiElement[] children = child.getChildren();
if (children.length == 1) {
items.add(children[0]);
} else {
// inalid for use: [$foo . $foo]
return new PsiElement[0];
}
}
}
return items.toArray(new PsiElement[0]);
}
/**
* array('foo' => FOO.class, 'foo1' => 'bar', 1 => 'foo')
*/
@NotNull
static public Map<String, PsiElement> getArrayKeyValueMapWithValueAsPsiElement(@NotNull ArrayCreationExpression arrayCreationExpression) {
HashMap<String, PsiElement> keys = new HashMap<>();
for(ArrayHashElement arrayHashElement: arrayCreationExpression.getHashElements()) {
PhpPsiElement child = arrayHashElement.getKey();
if(child != null && ((child instanceof StringLiteralExpression) || PhpPatterns.psiElement(PhpElementTypes.NUMBER).accepts(child))) {
String key;
if(child instanceof StringLiteralExpression) {
key = ((StringLiteralExpression) child).getContents();
} else {
key = child.getText();
}
if(key == null || StringUtils.isBlank(key)) {
continue;
}
keys.put(key, arrayHashElement.getValue());
}
}
return keys;
}
/**
* array('foo' => FOO.class, 'foo1' => 'bar', 1 => 'foo')
*/
@NotNull
static public Map<String, Pair<PsiElement, PsiElement>> getArrayKeyValueMapWithKeyAndValueElement(@NotNull ArrayCreationExpression arrayCreationExpression) {
HashMap<String, Pair<PsiElement, PsiElement>> keys = new HashMap<>();
for(ArrayHashElement arrayHashElement: arrayCreationExpression.getHashElements()) {
PhpPsiElement child = arrayHashElement.getKey();
if(child != null && ((child instanceof StringLiteralExpression) || PhpPatterns.psiElement(PhpElementTypes.NUMBER).accepts(child))) {
String key;
if(child instanceof StringLiteralExpression) {
key = ((StringLiteralExpression) child).getContents();
} else {
key = child.getText();
}
if(key == null || StringUtils.isBlank(key)) {
continue;
}
keys.put(key, new Pair(arrayHashElement.getKey(), arrayHashElement.getValue()));
}
}
return keys;
}
/**
* array('foo' => 'bar', 'foo1' => 'bar', 1 => 'foo')
*/
@NotNull
static public HashMap<String, String> getArrayKeyValueMap(@NotNull ArrayCreationExpression arrayCreationExpression) {
HashMap<String, String> keys = new HashMap<>();
for(ArrayHashElement arrayHashElement: arrayCreationExpression.getHashElements()) {
PhpPsiElement child = arrayHashElement.getKey();
if(child != null && ((child instanceof StringLiteralExpression) || PhpPatterns.psiElement(PhpElementTypes.NUMBER).accepts(child))) {
String key;
if(child instanceof StringLiteralExpression) {
key = ((StringLiteralExpression) child).getContents();
} else {
key = child.getText();
}
if(key == null || StringUtils.isBlank(key)) {
continue;
}
String value = null;
if(arrayHashElement.getValue() instanceof StringLiteralExpression) {
value = ((StringLiteralExpression) arrayHashElement.getValue()).getContents();
}
if(value == null || StringUtils.isBlank(value)) {
continue;
}
keys.put(key, value);
}
}
return keys;
}
@Nullable
static public PhpPsiElement getArrayValue(ArrayCreationExpression arrayCreationExpression, String name) {
for(ArrayHashElement arrayHashElement: arrayCreationExpression.getHashElements()) {
PhpPsiElement child = arrayHashElement.getKey();
if(child instanceof StringLiteralExpression) {
if(((StringLiteralExpression) child).getContents().equals(name)) {
return arrayHashElement.getValue();
}
}
}
return null;
}
@Nullable
static public String getArrayValueString(@NotNull ArrayCreationExpression arrayCreationExpression, @NotNull String name) {
PhpPsiElement phpPsiElement = getArrayValue(arrayCreationExpression, name);
if(phpPsiElement == null) {
return null;
}
if(phpPsiElement instanceof StringLiteralExpression) {
return ((StringLiteralExpression) phpPsiElement).getContents();
}
return null;
}
@Nullable
static public Boolean getArrayValueBool(@NotNull ArrayCreationExpression arrayCreationExpression, @NotNull String name) {
PhpPsiElement phpPsiElement = getArrayValue(arrayCreationExpression, name);
if(phpPsiElement == null) {
return null;
}
if (phpPsiElement instanceof ConstantReference) {
String lowerCase = phpPsiElement.getText().toLowerCase();
if (lowerCase.equals("true")) {
return true;
} else if (lowerCase.equals("false")) {
return false;
}
}
return null;
}
static public PhpNamedElement[] getPsiElementsBySignature(@NotNull Project project, @Nullable String signature) {
if(signature == null) {
return new PhpNamedElement[0];
}
Collection<? extends PhpNamedElement> phpNamedElementCollections = PhpIndex.getInstance(project).getBySignature(signature, null, 0);
return phpNamedElementCollections.toArray(new PhpNamedElement[0]);
}
@Nullable
static public PhpNamedElement getPsiElementsBySignatureSingle(Project project, @Nullable String signature) {
PhpNamedElement[] psiElements = getPsiElementsBySignature(project, signature);
if(psiElements.length == 0) {
return null;
}
return psiElements[0];
}
@Nullable
static public Method getClassMethod(@NotNull Project project, @NotNull String phpClassName, @NotNull String methodName) {
// we need here an each; because eg Command is non unique because phar file
for(PhpClass phpClass: PhpIndex.getInstance(project).getClassesByFQN(phpClassName)) {
Method method = phpClass.findMethodByName(methodName);
if(method != null) {
return method;
}
}
return null;
}
/**
* $this->methodName('service_name')
* $this->methodName(SERVICE::NAME)
* $this->methodName($this->name)
*/
static public boolean isMethodWithFirstStringOrFieldReference(PsiElement psiElement, String... methodName) {
if(!PlatformPatterns
.psiElement(PhpElementTypes.METHOD_REFERENCE)
.withChild(PlatformPatterns
.psiElement(PhpElementTypes.PARAMETER_LIST)
.withFirstChild(PlatformPatterns.or(
PlatformPatterns.psiElement(PhpElementTypes.STRING),
PlatformPatterns.psiElement(PhpElementTypes.FIELD_REFERENCE),
PlatformPatterns.psiElement(PhpElementTypes.CLASS_CONSTANT_REFERENCE)
))
).accepts(psiElement)) {
return false;
}
// cant we move it up to PlatformPatterns? withName condition dont looks working
String methodRefName = ((MethodReference) psiElement).getName();
return null != methodRefName && Arrays.asList(methodName).contains(methodRefName);
}
/**
*
* @deprecated use getMethodWithFirstStringOrNamedArgumentPattern
*/
@Deprecated
static public PsiElementPattern.Capture<StringLiteralExpression> getMethodWithFirstStringPattern() {
return PlatformPatterns
.psiElement(StringLiteralExpression.class)
.withParent(
PlatformPatterns.psiElement(PhpElementTypes.PARAMETER_LIST)
.withFirstChild(
PlatformPatterns.psiElement(PhpElementTypes.STRING)
)
.withParent(
PlatformPatterns.psiElement(PhpElementTypes.METHOD_REFERENCE)
)
)
.withLanguage(PhpLanguage.INSTANCE);
}
/**
* "$var->format(x: 'te<caret>st')"
* "$var->format($x, 'te<caret>st')"
* "$var->format('te<caret>st')"
*
* "not $var->format('', 'te<caret>st')"
*/
static public PsiElementPattern.Capture<StringLiteralExpression> getMethodWithFirstStringOrNamedArgumentPattern() {
return PlatformPatterns
.psiElement(StringLiteralExpression.class)
.withParent(
PlatformPatterns.psiElement(PhpElementTypes.PARAMETER_LIST)
)
.with(WITH_PREVIOUS_WHITESPACE_OR_COLON)
.withLanguage(PhpLanguage.INSTANCE);
}
/**
* "$var->format(x: 'te<caret>st')"
* "$var->format($x, 'te<caret>st')"
* "$var->format('te<caret>st')"
*/
static public PsiElementPattern.Capture<StringLiteralExpression> getMethodParameterListStringPattern() {
return PlatformPatterns
.psiElement(StringLiteralExpression.class)
.withParent(
PlatformPatterns.psiElement(PhpElementTypes.PARAMETER_LIST).withParent(
PlatformPatterns.psiElement(PhpElementTypes.METHOD_REFERENCE)
)
)
.withLanguage(PhpLanguage.INSTANCE);
}
static public PsiElementPattern.Capture<StringLiteralExpression> getFunctionWithFirstStringPattern(@NotNull String... functionName) {
return PlatformPatterns
.psiElement(StringLiteralExpression.class)
.withParent(
PlatformPatterns.psiElement(ParameterList.class)
.withFirstChild(
PlatformPatterns.psiElement(PhpElementTypes.STRING)
)
.withParent(
PlatformPatterns.psiElement(FunctionReference.class).with(new PatternCondition<>("function match") {
@Override
public boolean accepts(@NotNull FunctionReference functionReference, ProcessingContext processingContext) {
return ArrayUtils.contains(functionName, functionReference.getName());
}
})
)
)
.withLanguage(PhpLanguage.INSTANCE);
}
public static final PatternCondition<PsiElement> EMPTY_PREVIOUS_LEAF = new PatternCondition<>("previous leaf empty") {
@Override
public boolean accepts(@NotNull PsiElement stringLiteralExpression, ProcessingContext context) {
return stringLiteralExpression.getPrevSibling() == null;
}
};
/**
* #[Security("is_granted('POST_SHOW')")]
*/
@NotNull
public static PsiElementPattern.Capture<PsiElement> getFirstAttributeStringPattern(@NotNull String clazz) {
return PlatformPatterns.psiElement().withElementType(PlatformPatterns.elementType().or(
PhpTokenTypes.STRING_LITERAL_SINGLE_QUOTE,
PhpTokenTypes.STRING_LITERAL
))
.withParent(PlatformPatterns.psiElement(StringLiteralExpression.class)
.with(EMPTY_PREVIOUS_LEAF)
.withParent(PlatformPatterns.psiElement(ParameterList.class)
.withParent(PlatformPatterns.psiElement(PhpAttribute.class)
.with(new AttributeInstancePatternCondition(clazz))
)
)
);
}
/**
* #[Security("is_granted(['POST_SHOW'])")]
*/
@NotNull
public static PsiElementPattern.Capture<PsiElement> getFirstAttributeArrayStringPattern(@NotNull String clazz) {
return PlatformPatterns.psiElement().withElementType(PlatformPatterns.elementType().or(
PhpTokenTypes.STRING_LITERAL_SINGLE_QUOTE,
PhpTokenTypes.STRING_LITERAL
))
.withParent(PlatformPatterns.psiElement(StringLiteralExpression.class)
.withParent(PlatformPatterns.psiElement(PhpElementTypes.ARRAY_VALUE).withParent(
PlatformPatterns.psiElement(ArrayCreationExpression.class).with(EMPTY_PREVIOUS_LEAF).withParent(PlatformPatterns.psiElement(ParameterList.class)
.withParent(PlatformPatterns.psiElement(PhpAttribute.class)
.with(new AttributeInstancePatternCondition(clazz))
)
)
))
);
}
/**
* #[Security(foobar: "is_granted('POST_SHOW')")]
*/
@NotNull
public static PsiElementPattern.Capture<PsiElement> getAttributeNamedArgumentStringPattern(@NotNull String clazz, @NotNull String namedArgument) {
return PlatformPatterns.psiElement().withElementType(PlatformPatterns.elementType().or(
PhpTokenTypes.STRING_LITERAL_SINGLE_QUOTE,
PhpTokenTypes.STRING_LITERAL
))
.withParent(getAttributeNamedArgumentStringLiteralPattern(clazz, namedArgument));
}
/**
* #[Security(foobar: "is_granted('POST_SHOW')")]
*/
public static PsiElementPattern.@NotNull Capture<StringLiteralExpression> getAttributeNamedArgumentStringLiteralPattern(@NotNull String clazz, @NotNull String namedArgument) {
return PlatformPatterns.psiElement(StringLiteralExpression.class)
.afterLeafSkipping(
PlatformPatterns.psiElement(PsiWhiteSpace.class),
PlatformPatterns.psiElement(PhpTokenTypes.opCOLON).afterLeafSkipping(
PlatformPatterns.psiElement(PsiWhiteSpace.class),
PlatformPatterns.psiElement(PhpTokenTypes.IDENTIFIER).withText(namedArgument)
)
)
.withParent(PlatformPatterns.psiElement(ParameterList.class)
.withParent(PlatformPatterns.psiElement(PhpAttribute.class)
.with(new AttributeInstancePatternCondition(clazz))
)
);
}
/**
* "#[FOO(namedArgument: '<caret>'])]"
*/
public static PsiElementPattern.@NotNull Capture<StringLiteralExpression> getAttributeNamedArgumentStringLiteralPattern(@NotNull String namedArgument) {
return PlatformPatterns.psiElement(StringLiteralExpression.class)
.afterLeafSkipping(
PlatformPatterns.psiElement(PsiWhiteSpace.class),
PlatformPatterns.psiElement(PhpTokenTypes.opCOLON).afterLeafSkipping(
PlatformPatterns.psiElement(PsiWhiteSpace.class),
PlatformPatterns.psiElement(PhpTokenTypes.IDENTIFIER).withText(namedArgument)
)
)
.withParent(PlatformPatterns.psiElement(ParameterList.class)
.withParent(PlatformPatterns.psiElement(PhpAttribute.class))
);
}
/**
* #[Security(tags: ['foobar']])]
*/
@NotNull
public static PsiElementPattern.Capture<PsiElement> getAttributeNamedArgumentArrayStringPattern(@NotNull String clazz, @NotNull String namedArgument) {
return PlatformPatterns.psiElement().withElementType(PlatformPatterns.elementType().or(
PhpTokenTypes.STRING_LITERAL_SINGLE_QUOTE,
PhpTokenTypes.STRING_LITERAL
))
.withParent(PlatformPatterns.psiElement(StringLiteralExpression.class)
.withParent(PlatformPatterns.psiElement(PhpElementTypes.ARRAY_VALUE).withParent(
PlatformPatterns.psiElement(ArrayCreationExpression.class).afterLeafSkipping(
PlatformPatterns.psiElement(PsiWhiteSpace.class),
PlatformPatterns.psiElement(PhpTokenTypes.opCOLON).afterLeafSkipping(
PlatformPatterns.psiElement(PsiWhiteSpace.class),
PlatformPatterns.psiElement(PhpTokenTypes.IDENTIFIER).withText(namedArgument)
)
)
.withParent(PlatformPatterns.psiElement(ParameterList.class)
.withParent(PlatformPatterns.psiElement(PhpAttribute.class)
.with(new AttributeInstancePatternCondition(clazz))
)
)
))
);
}
@Nullable
public static String getClassDeprecatedMessage(@NotNull PhpClass phpClass) {
if (phpClass.isDeprecated()) {
PhpDocComment docComment = phpClass.getDocComment();
if (docComment != null) {
for (PhpDocTag deprecatedTag : docComment.getTagElementsByName("@deprecated")) {
// deprecatedTag.getValue provides a number !?
String tagValue = deprecatedTag.getText();
if (StringUtils.isNotBlank(tagValue)) {
String trim = tagValue.replace("@deprecated", "").trim();
if (StringUtils.isNotBlank(tagValue)) {
return StringUtils.abbreviate("Deprecated: " + trim, 100);
}
}
}
}
}
return null;
}
/**
* Check if given Attribute
*/
private static class AttributeInstancePatternCondition extends PatternCondition<PsiElement> {
private final String clazz;
AttributeInstancePatternCondition(@NotNull String clazz) {
super("Attribute Instance");
this.clazz = clazz;
}
@Override
public boolean accepts(@NotNull PsiElement psiElement, ProcessingContext processingContext) {
return clazz.equals(((PhpAttribute) psiElement).getFQN());
}
}
/**
* $foo->bar('<caret>')
*/
static public PsiElementPattern.Capture<PsiElement> getParameterInsideMethodReferencePattern() {
return PlatformPatterns
.psiElement()
.withParent(
PlatformPatterns.psiElement(StringLiteralExpression.class)
.withParent(
PlatformPatterns.psiElement(ParameterList.class)
.withParent(
PlatformPatterns.psiElement(MethodReference.class)
)
)
)
.withLanguage(PhpLanguage.INSTANCE);
}
static public PsiElementPattern.Capture<PsiElement> getParameterInsideNewExpressionPattern() {
return PlatformPatterns
.psiElement()
.withParent(
PlatformPatterns.psiElement(StringLiteralExpression.class)
.withParent(
PlatformPatterns.psiElement(ParameterList.class)
.withParent(
PlatformPatterns.psiElement(NewExpression.class)
)
)
)
.withLanguage(PhpLanguage.INSTANCE);
}
static public PsiElementPattern.Capture<PsiElement> getParameterInsideFunctionReferencePattern() {
return PlatformPatterns
.psiElement()
.withParent(
PlatformPatterns.psiElement(StringLiteralExpression.class)
.withParent(
PlatformPatterns.psiElement(ParameterList.class)
.withParent(
PlatformPatterns.psiElement(FunctionReference.class)
)
)
)
.withLanguage(PhpLanguage.INSTANCE);
}
/**
* class "Foo" extends
*/
static public PsiElementPattern.Capture<PsiElement> getClassNamePattern() {
return PlatformPatterns
.psiElement(PhpTokenTypes.IDENTIFIER)
.afterLeafSkipping(
PlatformPatterns.psiElement(PsiWhiteSpace.class),
PlatformPatterns.psiElement(PhpTokenTypes.kwCLASS)
)
.withParent(PhpClass.class)
.withLanguage(PhpLanguage.INSTANCE);
}
/**
* class Foo { function "test" {} }
*/
static public PsiElementPattern.Capture<PsiElement> getClassMethodNamePattern() {
return PlatformPatterns
.psiElement(PhpTokenTypes.IDENTIFIER)
.afterLeafSkipping(
PlatformPatterns.psiElement(PsiWhiteSpace.class),
PlatformPatterns.psiElement(PhpTokenTypes.kwFUNCTION)
)
.withParent(Method.class)
.withLanguage(PhpLanguage.INSTANCE);
}
/**
* return 'value' inside class method
*/
static public ElementPattern<PhpExpression> getMethodReturnPattern() {
return PlatformPatterns.or(
PlatformPatterns.psiElement(StringLiteralExpression.class)
.withParent(PlatformPatterns.psiElement(PhpReturn.class).inside(Method.class))
.withLanguage(PhpLanguage.INSTANCE),
PlatformPatterns.psiElement(ClassConstantReference.class)
.withParent(PlatformPatterns.psiElement(PhpReturn.class).inside(Method.class))
.withLanguage(PhpLanguage.INSTANCE)
);
}
/**
* Find a string return value of a method context "function() { return 'foo'}"
* First match wins
*/
@Nullable
static public String getMethodReturnAsString(@NotNull PhpClass phpClass, @NotNull String methodName) {
final Collection<String> values = getMethodReturnAsStrings(phpClass, methodName);
if(values.isEmpty()) {
return null;
}
// we support only first item
return values.iterator().next();
}
/**
* Find a string return value of a method context "function() { return 'foo'}"
*/
@NotNull
public static Collection<String> getMethodReturnAsStrings(@NotNull PhpClass phpClass, @NotNull String methodName) {
Method method = phpClass.findMethodByName(methodName);
if(method == null) {
return Collections.emptyList();
}
Set<String> values = new HashSet<>();
PhpControlFlowUtil.processFlow(method.getControlFlow(), new PhpInstructionProcessor() {
@Override
public boolean processReturnInstruction(PhpReturnInstruction instruction) {
PsiElement element = instruction.getArgument();
if(PhpElementsUtil.getMethodReturnPattern().accepts(element)) {
String value = PhpElementsUtil.getStringValue(element);
if(StringUtils.isNotBlank(value)) {
values.add(value);
}
}
return super.processReturnInstruction(instruction);
}
});
return values;
}
@Nullable
static public PhpClass getClass(Project project, String className) {
return getClass(PhpIndex.getInstance(project), className);
}
@Nullable
static public PhpClass getClass(PhpIndex phpIndex, String className) {
Collection<PhpClass> classes = phpIndex.getClassesByFQN(className);
return classes.isEmpty() ? null : classes.iterator().next();
}
@Nullable
static public PhpClass getInterface(PhpIndex phpIndex, String className) {
Collection<PhpClass> classes = phpIndex.getInterfacesByFQN(className);
return classes.isEmpty() ? null : classes.iterator().next();
}
@Nullable
static public PhpClass getClassInterface(Project project, @NotNull String className) {
Collection<PhpClass> phpClasses = PhpIndex.getInstance(project).getAnyByFQN(className);
return phpClasses.isEmpty() ? null : phpClasses.iterator().next();
}
/**
* @param subjectClass eg DateTime
* @param expectedClass eg DateTimeInterface
*/
public static boolean isInstanceOf(@NotNull PhpClass subjectClass, @NotNull PhpClass expectedClass) {
if (PhpLangUtil.equalsClassNames(subjectClass.getFQN(), expectedClass.getFQN())) {
return true;
}
Ref<Boolean> ref = new Ref<>(false);
PhpClassHierarchyUtils.processSupers(subjectClass, false, true, curClass -> {
ref.set(PhpLangUtil.equalsClassNames(curClass.getFQN(), expectedClass.getFQN()));
return !(Boolean) ref.get();
});
return ref.get();
}
/**
* @param subjectClass eg DateTime
* @param expectedClassAsString eg DateTimeInterface
*/
public static boolean isInstanceOf(@NotNull PhpClass subjectClass, @NotNull String expectedClassAsString) {
if (("\\" + StringUtils.stripStart(expectedClassAsString, "\\")).equals(subjectClass.getFQN())) {
return true;
}
for (PhpClass expectedClass : PhpIndex.getInstance(subjectClass.getProject()).getAnyByFQN(expectedClassAsString)) {
if (isInstanceOf(subjectClass, expectedClass)) {
return true;
}
}
return false;
}
public static boolean isInstanceOf(@NotNull PhpClass subjectClass, @NotNull String ...expectedClassAsString) {
return Arrays.stream(expectedClassAsString).anyMatch(clazz -> isInstanceOf(subjectClass, clazz));
}
/**
* @param subjectClassAsString eg DateTime
* @param expectedClass eg DateTimeInterface
*/
public static boolean isInstanceOf(@NotNull Project project, @NotNull String subjectClassAsString, @NotNull String expectedClass) {
if (("\\" + StringUtils.stripStart(subjectClassAsString, "\\")).equals(("\\" + StringUtils.stripStart(expectedClass, "\\")))) {
return true;
}
for (PhpClass subjectClass : PhpIndex.getInstance(project).getAnyByFQN(subjectClassAsString)) {
if (isInstanceOf(subjectClass, expectedClass)) {
return true;
}
}
return false;
}
static public Collection<PhpClass> getClassesInterface(Project project, @NotNull String className) {
return PhpIndex.getInstance(project).getAnyByFQN(className);
}
static public void addClassPublicMethodCompletion(CompletionResultSet completionResultSet, PhpClass phpClass) {
for(Method method: getClassPublicMethod(phpClass)) {
completionResultSet.addElement(new PhpLookupElement(method));
}
}
static public ArrayList<Method> getClassPublicMethod(PhpClass phpClass) {
ArrayList<Method> methods = new ArrayList<>();
for(Method method: phpClass.getMethods()) {
if(method.getAccess().isPublic() && !method.getName().startsWith("__")) {
methods.add(method);
}
}
return methods;
}
static public boolean hasClassConstantFields(@NotNull PhpClass phpClass) {
return phpClass.getFields().stream().anyMatch(Field::isConstant);
}
@Nullable
static public String getArrayHashValue(ArrayCreationExpression arrayCreationExpression, String keyName) {
ArrayHashElement translationArrayHashElement = PsiElementUtils.getChildrenOfType(arrayCreationExpression, PlatformPatterns.psiElement(ArrayHashElement.class)
.withFirstChild(
PlatformPatterns.psiElement(PhpElementTypes.ARRAY_KEY).withText(
PlatformPatterns.string().oneOf("'" + keyName + "'", "\"" + keyName + "\"")
)
)
);
if(translationArrayHashElement == null) {
return null;
}
if(!(translationArrayHashElement.getValue() instanceof StringLiteralExpression valueString)) {
return null;
}
return valueString.getContents();
}
static public boolean isEqualMethodReferenceName(MethodReference methodReference, String methodName) {
String name = methodReference.getName();
return name != null && name.equals(methodName);
}
@Nullable
static public String getArrayKeyValueInsideSignature(PsiElement psiElementInsideClass, String[] insideMethods, String methodName, String keyName) {
PhpClass phpClass = PsiTreeUtil.getParentOfType(psiElementInsideClass, PhpClass.class);
if (phpClass == null) {
return null;
}
for (String insideMethod : insideMethods) {
Method method = phpClass.findMethodByName(insideMethod);
if (method == null) {
continue;
}
for (MethodReference methodReference : collectMethodReferencesInsideControlFlow(method, methodName)) {
PsiElement[] parameters = methodReference.getParameters();
if (parameters.length > 0 && parameters[0] instanceof ArrayCreationExpression) {
PhpPsiElement arrayValue = PhpElementsUtil.getArrayValue((ArrayCreationExpression) parameters[0], keyName);
if (arrayValue != null) {
String stringValue = getStringValue(arrayValue);
if (stringValue != null && !stringValue.isBlank()) {
return stringValue;
}
}
}
}
}
return null;
}
public static Method[] getImplementedMethods(@NotNull Method method) {
ArrayList<Method> items = getImplementedMethods(method.getContainingClass(), method, new ArrayList<>(), new HashSet<>());
return items.toArray(new Method[0]);
}
private static ArrayList<Method> getImplementedMethods(@Nullable PhpClass phpClass, @NotNull Method method, ArrayList<Method> implementedMethods, Set<PhpClass> visitedClasses) {
if (phpClass == null || visitedClasses.contains(phpClass)) {
return implementedMethods;
}
visitedClasses.add(phpClass);
Method[] methods = phpClass.getOwnMethods();
for (Method ownMethod : methods) {
if (PhpLangUtil.equalsMethodNames(ownMethod.getName(), method.getName())) {
implementedMethods.add(ownMethod);
}
}
for(PhpClass interfaceClass: phpClass.getImplementedInterfaces()) {
getImplementedMethods(interfaceClass, method, implementedMethods, visitedClasses);
}
getImplementedMethods(phpClass.getSuperClass(), method, implementedMethods, visitedClasses);
return implementedMethods;
}
/**
* Resolve string definition in a recursive way
*
* $foo = Foo::class
* $this->foo = Foo::class
* $this->foo1 = $this->foo
*/
@Nullable
public static String getStringValue(@Nullable PsiElement psiElement) {
return getStringValue(psiElement, 0);
}
@Nullable
private static String getStringValue(@Nullable PsiElement psiElement, int depth) {
if(psiElement == null || ++depth > 5) {
return null;
}
if(psiElement instanceof StringLiteralExpression) {
String resolvedString = ((StringLiteralExpression) psiElement).getContents();
if(StringUtils.isEmpty(resolvedString)) {
return null;
}
return resolvedString;
} else if(psiElement instanceof Field) {
return getStringValue(((Field) psiElement).getDefaultValue(), depth);
} else if(psiElement instanceof ClassConstantReference && "class".equals(((ClassConstantReference) psiElement).getName())) {
// Foobar::class
return getClassConstantPhpFqn((ClassConstantReference) psiElement);
} else if(psiElement instanceof PhpReference) {
PsiReference psiReference = psiElement.getReference();
if(psiReference == null) {
return null;
}
PsiElement ref = psiReference.resolve();
if(ref instanceof PhpReference) {
return getStringValue(psiElement, depth);
}
if(ref instanceof Field) {
return getStringValue(((Field) ref).getDefaultValue());
}
}
return null;
}