Skip to content

add Twig "extends" generator action #1782

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 25, 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 @@ -19,10 +19,8 @@
import fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;
import fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil;
import fr.adrienbrault.idea.symfony2plugin.twig.utils.TwigFileUtil;
import icons.TwigIcons;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.List;
Expand All @@ -44,34 +42,14 @@ protected boolean isValidForFile(@NotNull Project project, @NotNull Editor edito
return Symfony2ProjectComponent.isEnabled(project) && (
file instanceof TwigFile
|| (file instanceof HtmlFileImpl && file.getName().toLowerCase().endsWith(".twig"))
|| getInjectedTwigElement(file, editor) != null
|| TwigUtil.getInjectedTwigElement(file, editor) != null
);
}

@Nullable
private static PsiElement getInjectedTwigElement(@NotNull PsiFile psiFile, @NotNull Editor editor) {
int caretOffset = editor.getCaretModel().getOffset();
if(caretOffset <= 0) {
return null;
}

PsiElement psiElement = psiFile.findElementAt(caretOffset - 1);
if(psiElement == null) {
return null;
}

return TwigUtil.getElementOnTwigViewProvider(psiElement);
}

private static class MyCodeInsightActionHandler implements CodeInsightActionHandler {
@Override
public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
int caretOffset = editor.getCaretModel().getOffset();
if(caretOffset <= 0) {
return;
}

PsiElement psiElement = getInjectedTwigElement(file, editor);
PsiElement psiElement = TwigUtil.getInjectedTwigElement(file, editor);
if(psiElement == null) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package fr.adrienbrault.idea.symfony2plugin.templating.action;

import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.actions.CodeInsightAction;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.html.HtmlFileImpl;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.ThrowableRunnable;
import com.intellij.util.indexing.FileBasedIndex;
import com.jetbrains.php.completion.insert.PhpInsertHandlerUtil;
import com.jetbrains.twig.TwigFile;
import fr.adrienbrault.idea.symfony2plugin.Symfony2ProjectComponent;
import fr.adrienbrault.idea.symfony2plugin.stubs.indexes.TwigExtendsStubIndex;
import fr.adrienbrault.idea.symfony2plugin.templating.util.TwigUtil;
import org.jetbrains.annotations.NotNull;

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

/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class TwigExtendsGenerator extends CodeInsightAction {
@Override
protected @NotNull
CodeInsightActionHandler getHandler() {
return new TwigExtendsGenerator.MyCodeInsightActionHandler();
}

@Override
protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
return Symfony2ProjectComponent.isEnabled(project) && (
file instanceof TwigFile
|| (file instanceof HtmlFileImpl && file.getName().toLowerCase().endsWith(".twig"))
|| TwigUtil.getInjectedTwigElement(file, editor) != null
);
}

private static class MyCodeInsightActionHandler implements CodeInsightActionHandler {
@Override
public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
PsiElement psiElement = TwigUtil.getInjectedTwigElement(file, editor);
if(psiElement == null) {
return;
}

Set<String> allKeys = FileBasedIndex.getInstance().getAllKeys(TwigExtendsStubIndex.KEY, project)
.stream()
.filter(s -> !s.toLowerCase().contains("@webprofiler") && !s.toLowerCase().contains("/profiler/") && !s.toLowerCase().contains("@twig") && !s.equalsIgnoreCase("form_div_layout.html.twig"))
.collect(Collectors.toSet());

Map<String, Integer> extendsWithFileCountUsage = new HashMap<>();
for (String allKey : allKeys) {
Collection<VirtualFile> containingFiles = FileBasedIndex.getInstance().getContainingFiles(TwigExtendsStubIndex.KEY, allKey, GlobalSearchScope.allScope(project));
extendsWithFileCountUsage.put(allKey, containingFiles.size());
}

List<String> prioritizedKeys = extendsWithFileCountUsage.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.map(Map.Entry::getKey)
.limit(40)
.collect(Collectors.toList());

if (prioritizedKeys.size() == 0) {
if (!ApplicationManager.getApplication().isHeadlessEnvironment()) {
HintManager.getInstance().showErrorHint(editor, "No extends found");
}

return;
}

JBPopupFactory.getInstance().createPopupChooserBuilder(prioritizedKeys)
.setTitle("Symfony: Twig Extends")
.setItemsChosenCallback(strings -> {
try {
WriteCommandAction.writeCommandAction(editor.getProject())
.withName("Twig Extends")
.run((ThrowableRunnable<Throwable>) () -> {
String content = strings.stream()
.map((Function<String, String>) s -> "{% extends '" + s + "' %}")
.collect(Collectors.joining("\n"));

PhpInsertHandlerUtil.insertStringAtCaret(editor, content);
});
} catch (Throwable ignored) {
}
})
.createPopup()
.showInBestPositionFor(editor);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

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;
Expand Down Expand Up @@ -2439,6 +2440,26 @@ public static Collection<PhpClass> getTwigExtensionClasses(@NotNull Project proj
.collect(Collectors.toCollection(HashSet::new));
}

@Nullable
public static PsiElement getInjectedTwigElement(@NotNull PsiFile psiFile, @NotNull Editor editor) {
int caretOffset = editor.getCaretModel().getOffset();
if(caretOffset < 0) {
return null;
}

// last and first element of file are tricky :)
if (caretOffset == 0) {
return psiFile;
}

PsiElement psiElement = psiFile.findElementAt(caretOffset - 1);
if(psiElement == null) {
return null;
}

return TwigUtil.getElementOnTwigViewProvider(psiElement);
}

/**
* Resolve html language injection
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import fr.adrienbrault.idea.symfony2plugin.translation.dict.TranslationUtil;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;
import java.util.stream.Collectors;
Expand All @@ -32,7 +31,7 @@ protected boolean isValidForFile(@NotNull Project project, @NotNull Editor edito
return Symfony2ProjectComponent.isEnabled(project) && (
file instanceof TwigFile
|| (file instanceof HtmlFileImpl && file.getName().toLowerCase().endsWith(".twig"))
|| getInjectedTwigElement(file, editor) != null
|| TwigUtil.getInjectedTwigElement(file, editor) != null
);
}

Expand All @@ -42,30 +41,10 @@ protected CodeInsightActionHandler getHandler() {
return new MyCodeInsightActionHandler();
}

@Nullable
private static PsiElement getInjectedTwigElement(@NotNull PsiFile psiFile, @NotNull Editor editor) {
int caretOffset = editor.getCaretModel().getOffset();
if(caretOffset <= 0) {
return null;
}

PsiElement psiElement = psiFile.findElementAt(caretOffset);
if(psiElement == null) {
return null;
}

return TwigUtil.getElementOnTwigViewProvider(psiElement);
}

private static class MyCodeInsightActionHandler implements CodeInsightActionHandler {
@Override
public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile psiFile) {
int caretOffset = editor.getCaretModel().getOffset();
if(caretOffset <= 0) {
return;
}

PsiElement psiElement = getInjectedTwigElement(psiFile, editor);
PsiElement psiElement = TwigUtil.getInjectedTwigElement(psiFile, editor);
if(psiElement == null) {
return;
}
Expand Down
7 changes: 7 additions & 0 deletions src/main/resources/META-INF/plugin.xml
Original file line number Diff line number Diff line change
Expand Up @@ -725,6 +725,13 @@
<add-to-group group-id="GenerateGroup"/>
</action>

<action icon="TwigIcons.TwigFileIcon"
id="SymfonyTwigExtendsGenerator"
class="fr.adrienbrault.idea.symfony2plugin.templating.action.TwigExtendsGenerator"
text="Extends Tag">
<add-to-group group-id="GenerateGroup"/>
</action>

</actions>
</idea-plugin>

Expand Down