Skip to content

provide incomplete "if" completion for Twig #1787

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@

import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
Expand Down Expand Up @@ -440,6 +441,13 @@ public void addCompletions(@NotNull CompletionParameters parameters, ProcessingC
PlatformPatterns.psiElement(TwigTokenTypes.TAG_NAME),
new IncompleteForCompletionProvider()
);

// {% if => "if app.debug"
extend(
CompletionType.BASIC,
PlatformPatterns.psiElement(TwigTokenTypes.TAG_NAME),
new IncompleteIfCompletionProvider()
);
}

private boolean isCompletionStartingMatch(@NotNull String fullText, @NotNull CompletionParameters completionParameters, int minLength) {
Expand Down Expand Up @@ -821,7 +829,7 @@ public boolean accepts(@NotNull String s, ProcessingContext processingContext) {
private class IncompleteForCompletionProvider extends CompletionProvider<CompletionParameters> {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, @NotNull ProcessingContext processingContext, @NotNull CompletionResultSet resultSet) {
if(!Symfony2ProjectComponent.isEnabled(completionParameters.getPosition())) {
if (!Symfony2ProjectComponent.isEnabled(completionParameters.getPosition())) {
return;
}

Expand All @@ -836,59 +844,99 @@ public boolean accepts(@NotNull String s, ProcessingContext processingContext) {
return;
}

Set<Map.Entry<String, PsiVariable>> entries = TwigTypeResolveUtil.collectScopeVariables(completionParameters.getPosition()).entrySet();
resultSet.addAllElements(processVariables(
completionParameters.getPosition(),
PhpType::isArray,
pair -> {
String var = pair.getValue().getFirst();
String unpluralize = StringUtil.unpluralize(var);
if (unpluralize != null) {
var = unpluralize;
}

Map<String, Pair<String, LookupElement>> arrays = new HashMap<>();
return String.format("for %s in %s", var, pair.getKey());
}
));
}
}

Project project = completionParameters.getPosition().getProject();
/**
* {% if => "if app.debug"
*/
private class IncompleteIfCompletionProvider extends CompletionProvider<CompletionParameters> {
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, @NotNull ProcessingContext processingContext, @NotNull CompletionResultSet resultSet) {
if(!Symfony2ProjectComponent.isEnabled(completionParameters.getPosition())) {
return;
}

for(Map.Entry<String, PsiVariable> entry: entries) {
Collection<PhpClass> classFromPhpTypeSet = PhpElementsUtil.getClassFromPhpTypeSet(project, entry.getValue().getTypes());
for (PhpClass phpClass : classFromPhpTypeSet) {
for(Method method: phpClass.getMethods()) {
if(!(!method.getModifier().isPublic() || method.getName().startsWith("set") || method.getName().startsWith("__"))) {
if (PhpType.isArray(PhpIndex.getInstance(project).completeType(project, method.getType(), new HashSet<>()))) {
String propertyShortcutMethodName = TwigTypeResolveUtil.getPropertyShortcutMethodName(method);
arrays.put(entry.getKey() + "." + propertyShortcutMethodName, Pair.create(propertyShortcutMethodName, new PhpTwigMethodLookupElement(method)));
}
resultSet.restartCompletionOnPrefixChange(StandardPatterns.string().longerThan(1).with(new PatternCondition<>("if startsWith") {
@Override
public boolean accepts(@NotNull String s, ProcessingContext processingContext) {
return "if".startsWith(s);
}
}));

if (!isCompletionStartingMatch("if", completionParameters, 2)) {
return;
}

resultSet.addAllElements(processVariables(
completionParameters.getPosition(),
PhpType::isBoolean,
entry -> String.format("if %s", entry.getKey())
));
}
}

@NotNull
private Collection<LookupElement> processVariables(@NotNull PsiElement psiElement, @NotNull Predicate<PhpType> filter, @NotNull Function<Map.Entry<String, Pair<String, LookupElement>>, String> map) {
Project project = psiElement.getProject();

Map<String, Pair<String, LookupElement>> arrays = new HashMap<>();
for(Map.Entry<String, PsiVariable> entry: TwigTypeResolveUtil.collectScopeVariables(psiElement).entrySet()) {
Collection<PhpClass> classFromPhpTypeSet = PhpElementsUtil.getClassFromPhpTypeSet(project, entry.getValue().getTypes());
for (PhpClass phpClass : classFromPhpTypeSet) {
for(Method method: phpClass.getMethods()) {
if(!(!method.getModifier().isPublic() || method.getName().startsWith("set") || method.getName().startsWith("__"))) {
if (filter.test(PhpIndex.getInstance(project).completeType(project, method.getType(), new HashSet<>()))) {
String propertyShortcutMethodName = TwigTypeResolveUtil.getPropertyShortcutMethodName(method);
arrays.put(entry.getKey() + "." + propertyShortcutMethodName, Pair.create(propertyShortcutMethodName, new PhpTwigMethodLookupElement(method)));
}
}
}

for(Field field: phpClass.getFields()) {
if(field.getModifier().isPublic()) {
if (PhpType.isArray(PhpIndex.getInstance(project).completeType(project, field.getType(), new HashSet<>()))) {
arrays.put(entry.getKey() + "." + field.getName(), Pair.create(field.getName(), new PhpTwigMethodLookupElement(field)));
}
for(Field field: phpClass.getFields()) {
if(field.getModifier().isPublic()) {
if (filter.test(PhpIndex.getInstance(project).completeType(project, field.getType(), new HashSet<>()))) {
arrays.put(entry.getKey() + "." + field.getName(), Pair.create(field.getName(), new PhpTwigMethodLookupElement(field)));
}
}
}
}
}

for (Map.Entry<String, Pair<String, LookupElement>> entry : arrays.entrySet()) {
String var = entry.getValue().getFirst();
String unpluralize = StringUtil.unpluralize(var);
if (unpluralize != null) {
var = unpluralize;
}
Collection<LookupElement> items = new ArrayList<>();

LookupElementPresentation lookupElementPresentation = new LookupElementPresentation();
entry.getValue().getSecond().renderElement(lookupElementPresentation);
for (Map.Entry<String, Pair<String, LookupElement>> entry : arrays.entrySet()) {
LookupElementPresentation lookupElementPresentation = new LookupElementPresentation();
entry.getValue().getSecond().renderElement(lookupElementPresentation);

Set<String> types = new HashSet<>();
PsiElement psiElement = entry.getValue().getSecond().getPsiElement();
if (psiElement instanceof PhpTypedElement) {
types.addAll(((PhpTypedElement) psiElement).getType().getTypes());
}
Set<String> types = new HashSet<>();
PsiElement typeElement = entry.getValue().getSecond().getPsiElement();
if (typeElement instanceof PhpTypedElement) {
types.addAll(((PhpTypedElement) typeElement).getType().getTypes());
}

String content = String.format("for %s in %s", var, entry.getKey());
LookupElementBuilder lookupElement = LookupElementBuilder.create(content)
.withIcon(lookupElementPresentation.getIcon())
.withStrikeoutness(lookupElementPresentation.isStrikeout())
.withTypeText(StringUtils.stripStart(TwigTypeResolveUtil.getTypeDisplayName(project, types), "\\"));
LookupElementBuilder lookupElement = LookupElementBuilder.create(map.apply(entry))
.withIcon(lookupElementPresentation.getIcon())
.withStrikeoutness(lookupElementPresentation.isStrikeout())
.withTypeText(StringUtils.stripStart(TwigTypeResolveUtil.getTypeDisplayName(project, types), "\\"));

resultSet.addElement(lookupElement);
}
items.add(lookupElement);
}

return items;
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,22 @@ public void testThatMacroImportProvidesCompletion() {
);
}

public void testThatIncompleteIfStatementIsCompletedWithVariables() {
assertCompletionContains(TwigFileType.INSTANCE, "\n" +
"{# @var \\Foo\\Template\\Foobar foobar #}\n" +
"{% if<caret> %}\n",
"if foobar.ready", "if foobar.readyStatus"
);
}

public void testThatIncompleteForStatementIsCompletedWithVariables() {
assertCompletionContains(TwigFileType.INSTANCE, "\n" +
"{# @var \\Foo\\Template\\Foobar foobar #}\n" +
"{% fo<caret> %}\n",
"for myfoo in foobar.myfoos", "for date in foobar.dates", "for item in foobar.items"
);
}

private void createWorkaroundFile(@NotNull String file, @NotNull String content) {

try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,40 @@ class Foo
{
const FOO = 'BAR';
}
}
}


namespace Foo\Template {

class Foobar
{
/**
* @var \DateTime[]
*/
public $items;

public bool $ready;

public function __construct(public array $myfoos)
{
}

public function getFoobar(): array
{
}

/**
* @return \DateTime[]
*/
public function getDates()
{
}

/**
* @return bool
*/
public function isReadyStatus()
{
}
}
}