-
-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathTwigUtil.java
3110 lines (2613 loc) · 124 KB
/
TwigUtil.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.templating.util;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileVisitor;
import com.intellij.patterns.ElementPattern;
import com.intellij.patterns.PlatformPatterns;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.*;
import com.intellij.util.Consumer;
import com.intellij.util.Processor;
import com.intellij.util.containers.ArrayListSet;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.FileBasedIndex;
import com.jetbrains.php.PhpIndex;
import com.jetbrains.php.lang.PhpFileType;
import com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment;
import com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag;
import com.jetbrains.php.lang.psi.PhpPsiUtil;
import com.jetbrains.php.lang.psi.elements.*;
import com.jetbrains.php.phpunit.PhpUnitUtil;
import com.jetbrains.twig.TwigFile;
import com.jetbrains.twig.TwigFileType;
import com.jetbrains.twig.TwigLanguage;
import com.jetbrains.twig.TwigTokenTypes;
import com.jetbrains.twig.elements.*;
import de.espend.idea.php.annotation.util.AnnotationUtil;
import fr.adrienbrault.idea.symfony2plugin.Settings;
import fr.adrienbrault.idea.symfony2plugin.action.comparator.ValueComparator;
import fr.adrienbrault.idea.symfony2plugin.asset.AssetDirectoryReader;
import fr.adrienbrault.idea.symfony2plugin.extension.TwigFileUsage;
import fr.adrienbrault.idea.symfony2plugin.extension.TwigNamespaceExtension;
import fr.adrienbrault.idea.symfony2plugin.extension.TwigNamespaceExtensionParameter;
import fr.adrienbrault.idea.symfony2plugin.stubs.SymfonyProcessors;
import fr.adrienbrault.idea.symfony2plugin.stubs.cache.FileIndexCaches;
import fr.adrienbrault.idea.symfony2plugin.stubs.dict.TemplateUsage;
import fr.adrienbrault.idea.symfony2plugin.stubs.indexes.*;
import fr.adrienbrault.idea.symfony2plugin.templating.TemplateLookupElement;
import fr.adrienbrault.idea.symfony2plugin.templating.TwigPattern;
import fr.adrienbrault.idea.symfony2plugin.templating.dict.*;
import fr.adrienbrault.idea.symfony2plugin.templating.path.TwigNamespaceSetting;
import fr.adrienbrault.idea.symfony2plugin.templating.path.TwigPath;
import fr.adrienbrault.idea.symfony2plugin.templating.variable.dict.PsiVariable;
import fr.adrienbrault.idea.symfony2plugin.twig.assets.TwigNamedAssetsServiceParser;
import fr.adrienbrault.idea.symfony2plugin.util.*;
import fr.adrienbrault.idea.symfony2plugin.util.dict.SymfonyBundle;
import fr.adrienbrault.idea.symfony2plugin.util.psi.PsiElementAssertUtil;
import fr.adrienbrault.idea.symfony2plugin.util.service.ServiceXmlParserFactory;
import fr.adrienbrault.idea.symfony2plugin.util.yaml.YamlHelper;
import icons.TwigIcons;
import kotlin.Triple;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.YAMLTokenTypes;
import org.jetbrains.yaml.YAMLUtil;
import org.jetbrains.yaml.psi.*;
import java.io.File;
import java.text.Collator;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static fr.adrienbrault.idea.symfony2plugin.templating.TwigPattern.captureVariableOrField;
import static fr.adrienbrault.idea.symfony2plugin.util.StringUtils.underscore;
/**
* @author Adrien Brault <[email protected]>
* @author Daniel Espendiller <[email protected]>
*/
public class TwigUtil {
public static final String DOC_SEE_REGEX_WITHOUT_SEE = "([-@\\./\\:\\w\\\\\\[\\]]+)[\\s]*";
/**
* Twig namespace for "non namespace"; its also a reserved value in Twig library
*/
public static final String MAIN = "__main__";
/**
* Twig namespace types; mainly switch for its prefix
*/
public enum NamespaceType {
BUNDLE, ADD_PATH
}
private static final ExtensionPointName<TwigNamespaceExtension> TWIG_NAMESPACE_EXTENSIONS = new ExtensionPointName<>(
"fr.adrienbrault.idea.symfony2plugin.extension.TwigNamespaceExtension"
);
public static final ExtensionPointName<TwigFileUsage> TWIG_FILE_USAGE_EXTENSIONS = new ExtensionPointName<>(
"fr.adrienbrault.idea.symfony2plugin.extension.TwigFileUsage"
);
private static final Key<CachedValue<Map<String, Set<VirtualFile>>>> TEMPLATE_CACHE_TWIG = new Key<>("TEMPLATE_CACHE_TWIG");
private static final Key<CachedValue<Map<String, Set<VirtualFile>>>> TEMPLATE_CACHE_ALL = new Key<>("TEMPLATE_CACHE_ALL");
private static final Key<CachedValue<List<String>>> SYMFONY_TEMPLATE_INCLUDE_LIST = new Key<>("SYMFONY_TEMPLATE_INCLUDE_LIST");
private static final Key<CachedValue<List<String>>> SYMFONY_TEMPLATE_EMBED_LIST = new Key<>("SYMFONY_TEMPLATE_EMBED_LIST");
private static final Key<CachedValue<List<String>>> SYMFONY_TEMPLATE_EXTENDS_LIST = new Key<>("SYMFONY_TEMPLATE_EXTENDS_LIST");
public static String[] CSS_FILES_EXTENSIONS = new String[] { "css", "less", "sass", "scss" };
public static String[] JS_FILES_EXTENSIONS = new String[] { "js", "dart", "coffee" };
public static String[] IMG_FILES_EXTENSIONS = new String[] { "png", "jpg", "jpeg", "gif", "svg"};
public static String TEMPLATE_ANNOTATION_CLASS = "\\Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Template";
public static class TwigPathNamespaceComparator implements Comparator<TwigPath> {
@Override
public int compare(TwigPath o1, TwigPath o2) {
Collator collator = Collator.getInstance();
collator.setStrength(Collator.SECONDARY);
return collator.compare(o1.getNamespace(), o2.getNamespace());
}
}
@NotNull
public static String[] getControllerMethodShortcut(@NotNull Method method) {
// indexAction
String methodName = method.getName();
PhpClass phpClass = method.getContainingClass();
if(null == phpClass) {
return new String[0];
}
// defaultController
// default/Folder/FolderController
String className = phpClass.getName();
if(!className.endsWith("Controller")) {
return new String[0];
}
String shortcutName = null;
String shortcutNameForOldNotation = null;
SymfonyBundleUtil symfonyBundleUtil = new SymfonyBundleUtil(method.getProject());
SymfonyBundle symfonyBundle = symfonyBundleUtil.getContainingBundle(phpClass);
if(symfonyBundle != null) {
// check if files is in <Bundle>/Controller/*
PhpClass bundleClass = symfonyBundle.getPhpClass();
if(!phpClass.getNamespaceName().startsWith(bundleClass.getNamespaceName() + "Controller\\")) {
return new String[0];
}
// strip the controller folder name
String templateFolderName = phpClass.getNamespaceName().substring(bundleClass.getNamespaceName().length() + 11);
// HomeBundle:default:indexes
// HomeBundle:default/Test:indexes
templateFolderName = templateFolderName.replace("\\", "/");
// Foobar without (.html.twig)
String templateName = className.substring(0, className.lastIndexOf("Controller"));
if(methodName.equals("__invoke")) {
// AppBundle::foo_bar.html.twig
shortcutName = String.format(
"%s::%s%s",
symfonyBundle.getName(),
underscore(templateFolderName),
underscore(templateName)
);
// AppBundle::FooBar.html.twig
shortcutNameForOldNotation = String.format(
"%s::%s%s",
symfonyBundle.getName(),
templateFolderName,
templateName
);
} else {
// FooBundle:foo_bar:foo_bar.html.twig
shortcutName = String.format(
"%s:%s%s:%s",
symfonyBundle.getName(),
underscore(templateFolderName),
underscore(templateName),
underscore(StringUtils.removeEnd(methodName, "Action"))
);
// FooBundle:FooBar:fooBar.html.twig
shortcutNameForOldNotation = String.format(
"%s:%s%s:%s",
symfonyBundle.getName(),
templateFolderName,
templateName,
StringUtils.removeEnd(methodName, "Action")
);
}
} else {
// https://github.com/sensiolabs/SensioFrameworkExtraBundle/blob/master/src/Templating/TemplateGuesser.php
String fqn = phpClass.getFQN();
Matcher matcher = Pattern.compile("Controller\\\\(.+)Controller$").matcher(fqn);
if(matcher.find()) {
String domain = matcher.group(1);
String matchController = domain.replaceAll("\\\\", "/");
String matchAction = null;
if (!"__invoke".equals(methodName)) {
matchAction = methodName.replaceAll("Action$", "");
matchAction = matchAction;
}
List<String> parts = new ArrayList<>(
Arrays.asList(matchController.split("/"))
);
if (matchAction != null) {
parts.add(matchAction);
}
shortcutNameForOldNotation = String.join("/", parts);
shortcutName = underscore(String.join("/", parts));
}
}
if (shortcutName == null || shortcutNameForOldNotation == null) {
return new String[0];
}
// @TODO: we should support types later on; but nicer
// HomeBundle:default:indexes.html.twig
return new String[] {
shortcutName + ".html.twig",
shortcutName + ".json.twig",
shortcutName + ".xml.twig",
shortcutName + ".text.twig", // emails
shortcutNameForOldNotation + ".html.twig",
shortcutNameForOldNotation + ".json.twig",
shortcutNameForOldNotation + ".xml.twig",
shortcutNameForOldNotation + ".text.twig", // emails
};
}
/**
* Extract Template names from PhpDocTag
*
* "@Template("foo.html.twig")"
* "@Template(template="foo.html.twig")"
*/
@Nullable
public static Pair<String, Collection<PsiElement>> getTemplateAnnotationFiles(@NotNull PhpDocTag phpDocTag) {
String template = AnnotationUtil.getPropertyValueOrDefault(phpDocTag, "template");
if(template == null) {
return null;
}
template = normalizeTemplateName(template);
return Pair.create(template, new HashSet<>(getTemplatePsiElements(phpDocTag.getProject(), template)));
}
/**
* Get templates on "@Template()" and on method attached to given PhpDocTag
*/
@NotNull
public static Map<String, Collection<PsiElement>> getTemplateAnnotationFilesWithSiblingMethod(@NotNull PhpDocTag phpDocTag) {
Map<String, Collection<PsiElement>> targets = new HashMap<>();
// template on direct PhpDocTag
Pair<String, Collection<PsiElement>> templateAnnotationFiles = TwigUtil.getTemplateAnnotationFiles(phpDocTag);
if(templateAnnotationFiles != null) {
targets.put(templateAnnotationFiles.getFirst(), templateAnnotationFiles.getSecond());
}
// templates on "Method" of PhpDocTag
PhpDocComment phpDocComment = PsiTreeUtil.getParentOfType(phpDocTag, PhpDocComment.class);
if(phpDocComment != null) {
PsiElement method = phpDocComment.getNextPsiSibling();
if(method instanceof Method) {
for (String name : TwigUtil.getControllerMethodShortcut((Method) method)) {
targets.put(name, new HashSet<>(getTemplatePsiElements(method.getProject(), name)));
}
}
}
return targets;
}
/**
* Finds a trans_default_domain definition in twig file
*
* "{% trans_default_domain "validators" %}"
*
* @param position current scope to search for: Twig file or embed scope
* @return file translation domain
*/
@Nullable
public static String getTransDefaultDomainOnScope(@NotNull PsiElement position) {
// {% embed 'foo.html.twig' with { foo: '<caret>'|trans } %}
PsiElement parent = position.getParent();
if(parent != null && parent.getNode().getElementType() == TwigElementTypes.LITERAL) {
PsiElement parent2 = parent.getParent();
if(parent2 != null && parent2.getNode().getElementType() == TwigElementTypes.EMBED_TAG) {
PsiElement firstParent = PsiTreeUtil.findFirstParent(parent, true, psiElement -> {
IElementType elementType = psiElement.getNode().getElementType();
return elementType != TwigElementTypes.EMBED_TAG && elementType != TwigElementTypes.EMBED_STATEMENT;
});
if(firstParent != null) {
position = firstParent;
}
}
}
// find embed or file scope
PsiElement scope = getTransDefaultDomainScope(position);
if(scope == null) {
return null;
}
for (PsiElement psiElement : scope.getChildren()) {
// filter parent trans_default_domain, it should be in file context
if(psiElement instanceof TwigCompositeElement && psiElement.getNode().getElementType() == TwigElementTypes.TAG) {
final String[] fileTransDomain = {null};
psiElement.acceptChildren(new PsiRecursiveElementWalkingVisitor() {
@Override
public void visitElement(PsiElement element) {
if(TwigPattern.getTransDefaultDomainPattern().accepts(element)) {
String text = PsiElementUtils.trimQuote(element.getText());
if(StringUtils.isNotBlank(text)) {
fileTransDomain[0] = text;
}
}
super.visitElement(element);
}
});
if(fileTransDomain[0] != null) {
return fileTransDomain[0];
}
}
}
return null;
}
/**
* "form(form.name)" => "form"
*/
@Nullable
public static PsiElement getTwigFunctionParameterIdentifierPsi(@NotNull PsiElement psiElement) {
// "form(form.name)" => "form"
TwigFieldReference childOfType = PsiTreeUtil.findChildOfType(psiElement, TwigFieldReference.class);
if (childOfType != null) {
TwigPsiReference owner = childOfType.getOwner();
if (owner != null) {
return owner.getFirstChild();
}
}
// "form(form)" => "form"
TwigVariableReference childOfType1 = PsiTreeUtil.findChildOfType(psiElement, TwigVariableReference.class);
if (childOfType1 != null) {
return childOfType1.getFirstChild();
}
return null;
}
/**
* Search Twig element to find use trans_default_domain and returns given string parameter
*/
@Nullable
public static String getTransDefaultDomainOnScopeOrInjectedElement(@NotNull PsiElement position) {
if(position.getContainingFile().getContainingFile().getFileType() == TwigFileType.INSTANCE) {
return getTransDefaultDomainOnScope(position);
}
PsiElement element = getElementOnTwigViewProvider(position);
if(element != null) {
return getTransDefaultDomainOnScope(element);
}
return null;
}
/**
* File Scope:
* {% trans_default_domain "foo" %}
*
* Embed:
* {embed 'foo.html.twig'}{% trans_default_domain "foo" %}{% endembed %}
*/
@Nullable
public static PsiElement getTransDefaultDomainScope(@NotNull PsiElement psiElement) {
return PsiTreeUtil.findFirstParent(psiElement, psiElement1 ->
psiElement1 instanceof PsiFile ||
(psiElement1 instanceof TwigCompositeElement && psiElement1.getNode().getElementType() == TwigElementTypes.EMBED_STATEMENT)
);
}
/**
* need a twig translation print block and search for default domain on parameter or trans_default_domain
*
* @param psiElement some print block like that 'a'|trans
* @return matched domain or "messages" fallback
*/
@NotNull
public static String getPsiElementTranslationDomain(@NotNull PsiElement psiElement) {
String domain = getDomainTrans(psiElement);
if(domain == null) {
domain = getTransDefaultDomainOnScope(psiElement);
}
return domain == null ? "messages" : domain;
}
/**
* Extract translation domain parameter
* trans({}, 'Domain')
* transchoice(2, {}, 'Domain')
*/
@Nullable
public static String getDomainTrans(@NotNull PsiElement psiElement) {
PsiElement filter = PsiElementUtils.getNextSiblingAndSkip(psiElement, TwigTokenTypes.FILTER, TwigTokenTypes.SINGLE_QUOTE, TwigTokenTypes.DOUBLE_QUOTE);
if(!PsiElementAssertUtil.isNotNullAndIsElementType(filter, TwigTokenTypes.FILTER)) {
return null;
}
PsiElement filterName = PsiTreeUtil.nextVisibleLeaf(filter);
if(!PsiElementAssertUtil.isNotNullAndIsElementType(filterName, TwigTokenTypes.IDENTIFIER)) {
return null;
}
// Elements that match a simple parameter foo(<caret>,)
IElementType[] skipArrayElements = {
TwigElementTypes.LITERAL, TwigTokenTypes.LBRACE_SQ, TwigTokenTypes.RBRACE_SQ, TwigTokenTypes.IDENTIFIER,
TwigElementTypes.VARIABLE_REFERENCE, TwigElementTypes.FIELD_REFERENCE
};
String filterNameText = filterName.getText();
if("trans".equalsIgnoreCase(filterNameText)) {
PsiElement brace = PsiTreeUtil.nextVisibleLeaf(filterName);
if (PsiElementAssertUtil.isNotNullAndIsElementType(brace, TwigTokenTypes.LBRACE)) {
PsiElement comma = PsiElementUtils.getNextSiblingAndSkip(brace, TwigTokenTypes.COMMA, skipArrayElements);
if(comma != null) {
String text = extractDomainFromParameter(comma);
if (text != null) {
return text;
}
}
}
} else if ("transchoice".equalsIgnoreCase(filterNameText)) {
PsiElement brace = PsiTreeUtil.nextVisibleLeaf(filterName);
if (PsiElementAssertUtil.isNotNullAndIsElementType(brace, TwigTokenTypes.LBRACE)) {
// skip elements which are possible a parameter variable and are between commas
IElementType[] skipElements = {
TwigTokenTypes.SINGLE_QUOTE, TwigTokenTypes.DOUBLE_QUOTE, TwigTokenTypes.NUMBER,
TwigTokenTypes.STRING_TEXT, TwigTokenTypes.DOT, TwigTokenTypes.IDENTIFIER,
TwigElementTypes.VARIABLE_REFERENCE, TwigElementTypes.FIELD_REFERENCE,
TwigTokenTypes.CONCAT, TwigTokenTypes.PLUS, TwigTokenTypes.MINUS,
};
PsiElement comma1 = PsiElementUtils.getNextSiblingAndSkip(brace, TwigTokenTypes.COMMA, skipElements);
if(comma1 != null) {
PsiElement comma2 = PsiElementUtils.getNextSiblingAndSkip(comma1, TwigTokenTypes.COMMA, skipArrayElements);
if(comma2 != null) {
String text = extractDomainFromParameter(comma2);
if (text != null) {
return text;
}
}
}
}
}
return null;
}
/**
* ({}, "foobar", )
*/
@Nullable
private static String extractDomainFromParameter(@NotNull PsiElement comma) {
if (PsiElementAssertUtil.isNotNullAndIsElementType(comma, TwigTokenTypes.COMMA)) {
PsiElement quote = PsiTreeUtil.nextVisibleLeaf(comma);
if (PsiElementAssertUtil.isNotNullAndIsElementType(quote, TwigTokenTypes.SINGLE_QUOTE, TwigTokenTypes.DOUBLE_QUOTE)) {
PsiElement text = PsiTreeUtil.nextVisibleLeaf(quote);
if (text != null && TwigPattern.getParameterAsStringPattern().accepts(text)) {
return text.getText();
}
}
}
return null;
}
/**
* {% import _self as %}
* {% import 'foobar.html.twig' as %}
*
* {% from _self import %}
* {% from 'forms.html' import %}
*/
private static Pair<String, PsiElement> getTemplateNameOnStringAndSelfWithNextPsiElement(@NotNull PsiElement tagPsiElement, @NotNull IElementType elementType) {
PsiElement lastElementMatch = null;
String template = null;
PsiElement selfPsi = PsiElementUtils.getNextSiblingAndSkip(tagPsiElement, TwigTokenTypes.RESERVED_ID);
if(selfPsi != null && "_self".equals(selfPsi.getText())) {
// {% import _self as foobar %}
template = "_self";
lastElementMatch = PsiElementUtils.getNextSiblingAndSkip(selfPsi, elementType);
} else {
// {% import 'foobar.html.twig' as foobar %}
PsiElement templateString = PsiElementUtils.getNextSiblingAndSkip(tagPsiElement, TwigTokenTypes.STRING_TEXT, TwigTokenTypes.SINGLE_QUOTE, TwigTokenTypes.DOUBLE_QUOTE);
if(templateString != null) {
String templateName = templateString.getText();
if(StringUtils.isNotBlank(templateName)) {
template = templateName;
lastElementMatch = PsiElementUtils.getNextSiblingAndSkip(templateString, elementType, TwigTokenTypes.SINGLE_QUOTE, TwigTokenTypes.DOUBLE_QUOTE);
}
}
}
if(lastElementMatch == null | lastElementMatch == null) {
return null;
}
return Pair.create(template, lastElementMatch);
}
/**
* {% from _self import foobar as input, foobar %}
* {% from 'foobar.html.twig' import foobar_twig %}
*/
@NotNull
public static Collection<TwigMacro> getImportedMacros(@NotNull PsiFile psiFile) {
PsiElement[] importPsiElements = PsiTreeUtil.collectElements(psiFile, paramPsiElement ->
PlatformPatterns.psiElement(TwigElementTypes.IMPORT_TAG).accepts(paramPsiElement)
);
if(importPsiElements.length == 0) {
return Collections.emptyList();
}
Collection<TwigMacro> macros = new ArrayList<>();
for(PsiElement psiImportTag: importPsiElements) {
PsiElement firstChild = psiImportTag.getFirstChild();
if(firstChild == null) {
continue;
}
PsiElement tagName = PsiElementUtils.getNextSiblingAndSkip(firstChild, TwigTokenTypes.TAG_NAME);
if(tagName == null || !"from".equals(tagName.getText())) {
continue;
}
Pair<String, PsiElement> pair = getTemplateNameOnStringAndSelfWithNextPsiElement(tagName, TwigTokenTypes.IMPORT_KEYWORD);
if(pair == null) {
continue;
}
String templateName = pair.getFirst();
// find end block to extract variables
PsiElement endBlock = PsiElementUtils.getNextSiblingOfType(
pair.getSecond(),
PlatformPatterns.psiElement().withElementType(TwigTokenTypes.STATEMENT_BLOCK_END)
);
if(endBlock == null) {
continue;
}
String substring = psiFile.getText().substring(pair.getSecond().getTextRange().getEndOffset(), endBlock.getTextOffset()).trim();
for(String macroName : substring.split(",")) {
// not nice here search for as "macro as macro_alias"
Matcher asMatcher = Pattern.compile("(\\w+)\\s+as\\s+(\\w+)").matcher(macroName.trim());
if(asMatcher.find()) {
macros.add(new TwigMacro(asMatcher.group(2), templateName, asMatcher.group(1)));
} else {
macros.add(new TwigMacro(macroName.trim(), templateName));
}
}
}
return macros;
}
/**
* Get targets for macro imports
*
* {% from _self import foobar as input, foobar %}
* {% from 'foobar.html.twig' import foobar_twig %}
*/
@NotNull
public static Collection<PsiElement> getImportedMacros(@NotNull PsiFile psiFile, @NotNull String funcName) {
Collection<PsiElement> psiElements = new ArrayList<>();
for (TwigMacro twigMacro : TwigUtil.getImportedMacros(psiFile)) {
if (!twigMacro.getName().equals(funcName)) {
continue;
}
// switch to alias mode
String macroName = twigMacro.getOriginalName() == null ? funcName : twigMacro.getOriginalName();
Collection<PsiFile> foreignPsiFile = new HashSet<>();
if ("_self".equals(twigMacro.getTemplate())) {
foreignPsiFile.add(psiFile);
} else {
foreignPsiFile.addAll(getTemplatePsiElements(psiFile.getProject(), twigMacro.getTemplate()));
}
for (PsiFile file : foreignPsiFile) {
visitMacros(file, pair -> {
if(macroName.equals(pair.getFirst().getName())) {
psiElements.add(pair.getSecond());
}
});
}
}
return psiElements;
}
/**
* {% import _self as foobar %}
* {% import 'foobar.html.twig' as foobar %}
*/
public static Collection<TwigMacro> getImportedMacrosNamespaces(@NotNull PsiFile psiFile) {
Collection<TwigMacro> macros = new ArrayList<>();
visitImportedMacrosNamespaces(psiFile, pair -> macros.add(pair.getFirst()));
return macros;
}
/**
* Find targets for given macros, alias supported
*
* {% import _self as foobar %}
* {{ foobar.bar() }}
*/
public static Collection<PsiElement> getImportedMacrosNamespaces(@NotNull PsiFile psiFile, @NotNull String macroName) {
Collection<PsiElement> macros = new ArrayList<>();
visitImportedMacrosNamespaces(psiFile, pair -> {
if(pair.getFirst().getName().equals(macroName)) {
macros.add(pair.getSecond());
}
});
return macros;
}
/**
* {% import _self as foobar %}
* {% import 'foobar.html.twig' as foobar %}
*/
private static void visitImportedMacrosNamespaces(@NotNull PsiFile psiFile, @NotNull Consumer<Pair<TwigMacro, PsiElement>> consumer) {
PsiElement[] importPsiElements = PsiTreeUtil.collectElements(psiFile, psiElement ->
psiElement.getNode().getElementType() == TwigElementTypes.IMPORT_TAG
);
for (PsiElement importPsiElement : importPsiElements) {
PsiElement firstChild = importPsiElement.getFirstChild();
if(firstChild == null) {
continue;
}
PsiElement tagName = PsiElementUtils.getNextSiblingAndSkip(firstChild, TwigTokenTypes.TAG_NAME);
if(tagName == null || !"import".equals(tagName.getText())) {
continue;
}
Collection<PsiFile> macroFiles = new HashSet<>();
Pair<String, PsiElement> pair = getTemplateNameOnStringAndSelfWithNextPsiElement(tagName, TwigTokenTypes.AS_KEYWORD);
if(pair == null) {
continue;
}
PsiElement asVariable = PhpPsiUtil.getNextSiblingIgnoreWhitespace(pair.getSecond(), true);
if(!(asVariable instanceof TwigPsiReference)) {
continue;
}
String asName = asVariable.getText();
String template = pair.getFirst();
// resolve _self and template name
if(template.equals("_self")) {
macroFiles.add(psiFile);
} else {
macroFiles.addAll(getTemplatePsiElements(psiFile.getProject(), template));
}
if(macroFiles.size() > 0) {
for (PsiFile macroFile : macroFiles) {
TwigUtil.visitMacros(macroFile, tagPair -> consumer.consume(Pair.create(
new TwigMacro(asName + '.' + tagPair.getFirst().getName(), template).withParameter(tagPair.getFirst().getParameters()),
tagPair.getSecond()
)));
}
}
}
}
/**
* {% set foobar = 'foo' %}
* {% set foo %}{% endset %}
*
* TODO: {% set foo, bar = 'foo', 'bar' %}
*/
@NotNull
public static Collection<String> getSetDeclaration(@NotNull PsiFile psiFile) {
Collection<String> sets = new ArrayList<>();
PsiElement[] psiElements = PsiTreeUtil.collectElements(psiFile, psiElement ->
psiElement.getNode().getElementType() == TwigElementTypes.SET_TAG
);
for (PsiElement psiElement : psiElements) {
PsiElement firstChild = psiElement.getFirstChild();
if(firstChild == null) {
continue;
}
PsiElement tagName = PsiElementUtils.getNextSiblingAndSkip(firstChild, TwigTokenTypes.TAG_NAME);
if(tagName == null || !"set".equals(tagName.getText())) {
continue;
}
PsiElement setVariable = PhpPsiUtil.getNextSiblingIgnoreWhitespace(tagName, true);
if(!(setVariable instanceof TwigPsiReference)) {
continue;
}
String text = setVariable.getText();
if(StringUtils.isNotBlank(text)) {
sets.add(text);
}
}
return sets;
}
/**
* Find a controller method which possibly rendered the tempalte
*
* Foobar/Bar.html.twig" => FoobarController::barAction
* Foobar/Bar.html.twig" => FoobarController::bar
* Foobar.html.twig" => FoobarController::__invoke
*/
@NotNull
public static Collection<Method> findTwigFileController(@NotNull TwigFile twigFile) {
SymfonyBundle symfonyBundle = new SymfonyBundleUtil(twigFile.getProject()).getContainingBundle(twigFile);
if(symfonyBundle == null) {
return Collections.emptyList();
}
String relativePath = symfonyBundle.getRelativePath(twigFile.getVirtualFile());
if(relativePath == null || !relativePath.startsWith("Resources/views/")) {
return Collections.emptyList();
}
String viewPath = relativePath.substring("Resources/views/".length());
String className = null;
Collection<String> methodNames = new ArrayList<>();
Matcher methodMatcher = Pattern.compile(".*/(\\w+)\\.\\w+\\.twig").matcher(viewPath);
if(methodMatcher.find()) {
// Foobar/Bar.html.twig" => FoobarController::barAction
// Foobar/Bar.html.twig" => FoobarController::bar
methodNames.add(methodMatcher.group(1) + "Action");
methodNames.add(methodMatcher.group(1));
className = String.format(
"%sController\\%sController",
symfonyBundle.getNamespaceName(),
viewPath.substring(0, viewPath.lastIndexOf("/")).replace("/", "\\")
);
} else {
// Foobar.html.twig" => FoobarController::__invoke
Matcher invokeMatcher = Pattern.compile("^(\\w+)\\.\\w+\\.twig").matcher(viewPath);
if(invokeMatcher.find()) {
className = String.format(
"%sController\\%sController",
symfonyBundle.getNamespaceName(),
invokeMatcher.group(1)
);
methodNames.add("__invoke");
}
}
// found not valid template name pattern
if(className == null || methodNames.size() == 0) {
return Collections.emptyList();
}
// find multiple targets
Collection<Method> methods = new HashSet<>();
for (String methodName : methodNames) {
Method method = PhpElementsUtil.getClassMethod(twigFile.getProject(), className, methodName);
if(method != null) {
methods.add(method);
}
}
return methods;
}
public static Map<String, PsiVariable> collectControllerTemplateVariables(@NotNull TwigFile twigFile) {
Map<String, PsiVariable> vars = new HashMap<>();
for (Method method : findTwigFileController(twigFile)) {
vars.putAll(PhpMethodVariableResolveUtil.collectMethodVariables(method));
}
for(Function methodIndex : getTwigFileMethodUsageOnIndex(twigFile)) {
vars.putAll(PhpMethodVariableResolveUtil.collectMethodVariables(methodIndex));
}
return vars;
}
/**
* Collect function variables scopes for given Twig file
*/
@NotNull
public static Set<Function> getTwigFileMethodUsageOnIndex(@NotNull TwigFile twigFile) {
return getTwigFileMethodUsageOnIndex(twigFile.getProject(), getTemplateNamesForFile(twigFile));
}
/**
* Collect function scopes to search for Twig variable of given template names: "foo.html.twig"
*/
@NotNull
public static Set<Function> getTwigFileMethodUsageOnIndex(@NotNull Project project, @NotNull Collection<String> keys) {
if(keys.size() == 0) {
return Collections.emptySet();
}
final Set<String> fqn = new HashSet<>();
for(String key: keys) {
for (TemplateUsage usage : FileBasedIndex.getInstance().getValues(PhpTwigTemplateUsageStubIndex.KEY, key, GlobalSearchScope.allScope(project))) {
fqn.addAll(usage.getScopes());
}
}
final Set<Function> methods = new HashSet<>();
for (String s : fqn) {
// function: "\foo"
if(!s.contains(".")) {
methods.addAll(PhpIndex.getInstance(project).getFunctionsByFQN("\\" + s));
continue;
}
// classes: "\foo.action"
String[] split = s.split("\\.");
if(split.length != 2) {
continue;
}
Method method = PhpElementsUtil.getClassMethod(project, split[0], split[1]);
if(method == null) {
continue;
}
methods.add(method);
}
return methods;
}
@Nullable
public static String getFoldingTemplateNameOrCurrent(@Nullable String templateName) {
String foldingName = getFoldingTemplateName(templateName);
return foldingName != null ? foldingName : templateName;
}
@Nullable
public static String getFoldingTemplateName(@Nullable String content) {
if(content == null || content.length() == 0) return null;
String templateShortcutName = null;
if(content.endsWith(".html.twig") && content.length() > 10) {
templateShortcutName = content.substring(0, content.length() - 10);
} else if(content.endsWith(".html.php") && content.length() > 9) {
templateShortcutName = content.substring(0, content.length() - 9);
}
if(templateShortcutName == null || templateShortcutName.length() == 0) {
return null;
}
// template FooBundle:Test:edit.html.twig
if(templateShortcutName.length() <= "Bundle:".length()) {
return templateShortcutName;
}
int split = templateShortcutName.indexOf("Bundle:");
if(split > 0) {
templateShortcutName = templateShortcutName.substring(0, split) + templateShortcutName.substring("Bundle".length() + split);
}
return templateShortcutName;
}
@NotNull
public static String getPresentableTemplateName(@NotNull PsiElement psiElement, boolean shortMode) {
VirtualFile currentFile = psiElement.getContainingFile().getVirtualFile();
List<String> templateNames = new ArrayList<>(
getTemplateNamesForFile(psiElement.getProject(), currentFile)
);
if(templateNames.size() > 0) {
// bundle names wins
if(templateNames.size() > 1) {
templateNames.sort(new TemplateStringComparator());
}
String templateName = templateNames.iterator().next();
if(shortMode) {
String shortName = getFoldingTemplateName(templateName);
if(shortName != null) {
return shortName;
}
}
return templateName;
}
String relativePath = VfsUtil.getRelativePath(currentFile, ProjectUtil.getProjectDir(psiElement), '/');
return relativePath != null ? relativePath : currentFile.getPath();
}
/**
* Generate a mapped template name file multiple relation:
*
* foo.html.twig => ["views/foo.html.twig", "templates/foo.html.twig"]
*/
@NotNull
public static Map<String, Set<VirtualFile>> getTemplateMap(@NotNull Project project) {
return getTemplateMap(project, false);
}
/**
* Generate a mapped template name file multiple relation:
*
* foo.html.twig => ["views/foo.html.twig", "templates/foo.html.twig"]
*/
@NotNull
public static synchronized Map<String, Set<VirtualFile>> getTemplateMap(@NotNull Project project, boolean usePhp) {
Map<String, Set<VirtualFile>> templateMapProxy;
// cache twig and all files,
// only PHP files we dont need to cache
if(!usePhp) {
templateMapProxy = CachedValuesManager.getManager(project).getCachedValue(
project,
TEMPLATE_CACHE_TWIG,
new MyAllTemplateFileMapCachedValueProvider(project),
false
);
} else {
// cache all files
templateMapProxy = CachedValuesManager.getManager(project).getCachedValue(
project,
TEMPLATE_CACHE_ALL,
new MyAllTemplateFileMapCachedValueProvider(project, true),
false
);
}
return templateMapProxy;
}
/**