下面列出了com.intellij.psi.util.PsiTreeUtil#collectElementsOfType ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void invokeInsert(YAMLFile yamlFile) {
Collection<YAMLKeyValue> yamlKeyValues = PsiTreeUtil.collectElementsOfType(yamlFile, YAMLKeyValue.class);
final YamlUpdateArgumentServicesCallback callback = new YamlUpdateArgumentServicesCallback(
getProject(),
ContainerUtil.find(yamlKeyValues, new YAMLKeyValueCondition("arguments")),
ContainerUtil.find(yamlKeyValues, new YAMLKeyValueCondition("foo"))
);
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
callback.insert(Arrays.asList("foo", "bar"));
}
});
}
}, null, null);
}
static List<NASMStructure> findStructures(Project project) {
List<NASMStructure> result = new ArrayList<>();
Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(
FileTypeIndex.NAME, NASMFileType.INSTANCE, GlobalSearchScope.allScope(project)
);
for (VirtualFile virtualFile : virtualFiles) {
NASMFile assemblyFile = (NASMFile)PsiManager.getInstance(project).findFile(virtualFile);
if (assemblyFile != null) {
Collection<NASMStructure> nasmStructs = PsiTreeUtil.collectElementsOfType(assemblyFile, NASMStructure.class);
if (!nasmStructs.isEmpty()) {
result.addAll(nasmStructs);
}
}
}
return result;
}
@NotNull
public List<BashPsiElement> findReferencedParameters() {
if (referencedParameters == null) {
synchronized (stateLock) {
if (referencedParameters == null) {
//call the visitor to find all uses of the parameter variables, take care no to collect parameters used in inner functions
List<BashPsiElement> newReferencedParameters = Lists.newLinkedList();
for (BashVar var : PsiTreeUtil.collectElementsOfType(this, BashVar.class)) {
if (var.isParameterReference() && this.equals(BashPsiUtils.findParent(var, BashFunctionDef.class, BashFunctionDef.class))) {
newReferencedParameters.add(var);
}
}
referencedParameters = newReferencedParameters;
}
}
}
return referencedParameters;
}
@NotNull
@Override
public DataIndexer<String, Set<Integer>, FileContent> getIndexer() {
return fileContent -> {
Set<Integer> offsets = new HashSet<>();
List<PsiElement> steps = new ArrayList<>();
PsiFile psiFile;
try {
psiFile = ((FileContentImpl) fileContent).createFileFromText(FileUtils.readFileToString(new File(fileContent.getFile().getPath()), Constants.FILE_ENCODING));
} catch (IOException e) {
return Collections.emptyMap();
}
if (fileContent.getFileType() instanceof SpecFileType)
steps = new ArrayList<>(PsiTreeUtil.collectElementsOfType(psiFile, SpecStepImpl.class));
else if (fileContent.getFileType() instanceof ConceptFileType)
steps = new ArrayList<>(PsiTreeUtil.collectElementsOfType(psiFile, ConceptStepImpl.class));
steps.forEach((s) -> offsets.add(s.getTextOffset()));
return Collections.singletonMap(fileContent.getFile().getPath(), offsets);
};
}
static List<NASMDefine> findPreprocessorDefines(PsiFile containingFile) {
List<NASMDefine> result = new ArrayList<>();
// Check the containing file's preprocessor defines
Collection<NASMDefine> nasmDefines = PsiTreeUtil.collectElementsOfType(containingFile, NASMDefine.class);
if (!nasmDefines.isEmpty())
result.addAll(nasmDefines);
// Makes this plugin perform like shit
//Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(
// FileTypeIndex.NAME, NASMFileType.INSTANCE, GlobalSearchScope.allScope(project)
//);
//for (VirtualFile virtualFile : virtualFiles) {
// NASMFile assemblyFile = (NASMFile)PsiManager.getInstance(project).findFile(virtualFile);
// if (assemblyFile != null) {
// Collection<NASMPreprocessor> nasmPreprocessors = PsiTreeUtil.collectElementsOfType(assemblyFile, NASMPreprocessor.class);
// if (!nasmPreprocessors.isEmpty()) {
// for (NASMPreprocessor nasmPreprocessor : nasmPreprocessors) {
// NASMDefine define = nasmPreprocessor.getDefine();
// if (define != null)
// result.add(define);
// }
// }
// }
//}
return result;
}
public void testYamlServiceArgumentCreation() {
YAMLFile yamlFile = YAMLElementGenerator.getInstance(getProject()).createDummyYamlWithText("" +
"services:\n" +
" foo:\n" +
" class: Foo\\Foo\n"
);
Collection<YAMLKeyValue> yamlKeyValues = PsiTreeUtil.collectElementsOfType(yamlFile, YAMLKeyValue.class);
YAMLKeyValue services = ContainerUtil.find(yamlKeyValues, new YamlUpdateArgumentServicesCallbackTest.YAMLKeyValueCondition("foo"));
assertNotNull(services);
final YamlCreateServiceArgumentsCallback callback = new YamlCreateServiceArgumentsCallback(services);
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
callback.insert(Arrays.asList("foo", null, ""));
}
});
}
}, null, null);
assertEquals("" +
"services:\n" +
" foo:\n" +
" class: Foo\\Foo\n" +
" arguments:\n" +
" ['@foo', '@?', '@?']\n",
yamlFile.getText()
);
}
static List<NASMIdentifier> findIdentifierReferences(PsiFile containingFile, NASMIdentifier identifier) {
List<NASMIdentifier> result = new ArrayList<>();
PsiElement targetIdentifierId = identifier.getNameIdentifier();
// First check the containing file's identifiers
Collection<NASMIdentifier> nasmIdentifiers = PsiTreeUtil.collectElementsOfType(containingFile, NASMIdentifier.class);
for (NASMIdentifier nasmIdentifier : nasmIdentifiers) {
if (nasmIdentifier != identifier) {
if (targetIdentifierId.getText().equals(nasmIdentifier.getNameIdentifier().getText())) {
result.add(nasmIdentifier);
}
}
}
return result;
}
static List<NASMIdentifier> findIdentifierReferencesById(PsiFile containingFile, String targetIdentifierId) {
List<NASMIdentifier> result = null;
// First check the containing file's identifiers
Collection<NASMIdentifier> identifiers = PsiTreeUtil.collectElementsOfType(containingFile, NASMIdentifier.class);
for (NASMIdentifier identifier : identifiers) {
if (targetIdentifierId.equals(identifier.getId().getText())) {
if (result == null) {
result = new ArrayList<>();
}
result.add(identifier);
}
}
return result != null ? result : Collections.emptyList();
}
static List<NASMIdentifier> findIdentifierReferencesInProject(Project project) {
List<NASMIdentifier> result = new ArrayList<>();
Collection<VirtualFile> virtualFiles = FileBasedIndex.getInstance().getContainingFiles(FileTypeIndex.NAME,
NASMFileType.INSTANCE, GlobalSearchScope.allScope(project));
for (VirtualFile virtualFile : virtualFiles) {
NASMFile nasmFile = (NASMFile)PsiManager.getInstance(project).findFile(virtualFile);
if (nasmFile != null) {
Collection<NASMIdentifier> nasmIdentifiers = PsiTreeUtil.collectElementsOfType(nasmFile, NASMIdentifier.class);
result.addAll(nasmIdentifiers);
}
}
return result;
}
@Nullable
public static PhpClass getFirstTestClassFromFile(PhpFile phpFile) {
Collection<PhpClass> phpClasses = PsiTreeUtil.collectElementsOfType(phpFile, PhpClass.class);
for (PhpClass phpClass:phpClasses) {
if (isClassAtoumTest(phpClass)) {
return phpClass;
}
}
return null;
}
/**
* Get attributes for @Foo("test", ATTR<caret>IBUTE)
*
* "@Attributes(@Attribute("accessControl", type="string"))"
* "@Attributes({@Attribute("accessControl", type="string")})"
* "class foo { public $foo; }"
*/
public static void visitAttributes(@NotNull PhpClass phpClass, TripleFunction<String, String, PsiElement, Void> fn) {
for (Field field : phpClass.getFields()) {
if(field.getModifier().isPublic() && !field.isConstant()) {
String type = null;
for (String type2 : field.getType().filterNull().getTypes()) {
if (PhpType.isPrimitiveType(type2)) {
type = StringUtils.stripStart(type2, "\\");
}
}
fn.fun(field.getName(), type, field);
}
}
PhpDocComment docComment = phpClass.getDocComment();
if (docComment != null) {
for (PhpDocTag phpDocTag : docComment.getTagElementsByName("@Attributes")) {
for (PhpDocTag docTag : PsiTreeUtil.collectElementsOfType(phpDocTag, PhpDocTag.class)) {
String name = docTag.getName();
if (!"@Attribute".equals(name)) {
continue;
}
String defaultPropertyValue = AnnotationUtil.getDefaultPropertyValue(docTag);
if (defaultPropertyValue == null || StringUtils.isBlank(defaultPropertyValue)) {
continue;
}
fn.fun(defaultPropertyValue, AnnotationUtil.getPropertyValue(docTag, "type"), docTag);
}
}
}
}
@Override
protected void addCompletions(CompletionParameters parameters, ProcessingContext processingContext, CompletionResultSet resultSet) {
String prefix = getPrefix(parameters);
resultSet = resultSet.withPrefixMatcher(new PlainPrefixMatcher(prefix));
Collection<ConceptStaticArg> staticArgs = PsiTreeUtil.collectElementsOfType(parameters.getOriginalFile(), ConceptStaticArg.class);
for (ConceptStaticArg arg : staticArgs) {
if (arg != null) {
String text = arg.getText().replaceFirst("\"", "");
String textWithoutQuotes = text.substring(0, text.length() - 1);
if (!textWithoutQuotes.equals(""))
resultSet.addElement(LookupElementBuilder.create(textWithoutQuotes));
}
}
}
public void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet resultSet) {
String prefix = getPrefix(parameters);
resultSet = resultSet.withPrefixMatcher(new PlainPrefixMatcher(prefix));
Collection<ConceptDynamicArg> args = PsiTreeUtil.collectElementsOfType(parameters.getOriginalFile(), ConceptDynamicArg.class);
for (ConceptDynamicArg arg : args) {
LookupElementBuilder item = LookupElementBuilder.create(arg.getText().replaceAll("<|>", ""));
resultSet.addElement(item);
}
}
@Override
public void collectSlowLineMarkers(@NotNull List<PsiElement> elements, @NotNull Collection<LineMarkerInfo> result) {
for(PsiElement psiElement : elements) {
List<GotoRelatedItem> gotoRelatedItems = new ArrayList<GotoRelatedItem>();
List<PsiFile> psiFiles = new ArrayList<PsiFile>();
// android studio provide line marker with xml targets only on root classes not on class inside classes like fragments
// we support all of them :)
if(psiElement instanceof PsiIdentifier && psiElement.getParent() instanceof PsiClass && !(psiElement.getParent().getParent() instanceof PsiFile)) {
// simple hack activity provide this on core
if(isFragmentClass((PsiClass) psiElement.getParent())) {
Collection<PsiMethodCallExpression> PsiMethodCallExpressions = PsiTreeUtil.collectElementsOfType(psiElement.getParent(), PsiMethodCallExpression.class);
for(PsiMethodCallExpression methodCallExpression: PsiMethodCallExpressions) {
PsiMethod psiMethod = methodCallExpression.resolveMethod();
if(psiMethod != null && psiMethod.getName().equals("inflate")) {
PsiExpression[] expressions = methodCallExpression.getArgumentList().getExpressions();
if(expressions.length > 0 && expressions[0] instanceof PsiReferenceExpression) {
PsiFile xmlFile = AndroidUtils.findXmlResource((PsiReferenceExpression) expressions[0]);
if(xmlFile != null && !psiFiles.contains(xmlFile)) {
psiFiles.add(xmlFile);
gotoRelatedItems.add(new GotoRelatedItem(xmlFile));
}
}
}
}
}
}
if(gotoRelatedItems.size() > 0) {
result.add(new LineMarkerInfo<PsiElement>(psiElement, psiElement.getTextOffset(), AndroidIcons.AndroidToolWindow, 6, new ConstantFunction<PsiElement, String>("Related Files"), new RelatedPopupGotoLineMarker.NavigationHandler(gotoRelatedItems)));
}
}
}
/**
* Find methodReferences in scope by its name and method scope and give string value of matching parameter
*
* $resolver->setDefault('data_class', User::class);
*/
@NotNull
public static Collection<String> getMethodReferenceStringParameter(@NotNull PsiElement scope, String[] scopeMethods, @NotNull String methodName, @NotNull String key) {
PhpClass phpClass = PsiTreeUtil.getParentOfType(scope, PhpClass.class);
if(phpClass == null) {
return Collections.emptyList();
}
Collection<String> values = new HashSet<>();
for (String scopeMethod : scopeMethods) {
Method method = phpClass.findMethodByName(scopeMethod);
if(method == null) {
continue;
}
for (MethodReference methodReference : PsiTreeUtil.collectElementsOfType(method, MethodReference.class)) {
if(!methodName.equals(methodReference.getName())) {
continue;
}
// our key to find
String argument = PhpElementsUtil.getMethodReferenceStringValueParameter(methodReference, 0);
if(!key.equals(argument)) {
continue;
}
// resolve value
String value = PhpElementsUtil.getMethodReferenceStringValueParameter(methodReference, 1);
if(StringUtils.isBlank(value)) {
continue;
}
values.add(value);
}
}
return values;
}
public void parse(File file) {
VirtualFile virtualFile = VfsUtil.findFileByIoFile(file, true);
if(virtualFile == null) {
Symfony2ProjectComponent.getLogger().info("VfsUtil missing translation: " + file.getPath());
return;
}
PsiFile psiFile;
try {
psiFile = PhpPsiElementFactory.createPsiFileFromText(this.project, StreamUtil.readText(virtualFile.getInputStream(), "UTF-8"));
} catch (IOException e) {
return;
}
if(psiFile == null) {
return;
}
Symfony2ProjectComponent.getLogger().info("update translations: " + file.getPath());
Collection<NewExpression> messageCatalogues = PsiTreeUtil.collectElementsOfType(psiFile, NewExpression.class);
for(NewExpression newExpression: messageCatalogues) {
ClassReference classReference = newExpression.getClassReference();
if(classReference != null) {
PsiElement constructorMethod = classReference.resolve();
if(constructorMethod instanceof Method) {
PhpClass phpClass = ((Method) constructorMethod).getContainingClass();
if(phpClass != null && PhpElementsUtil.isInstanceOf(phpClass, "\\Symfony\\Component\\Translation\\MessageCatalogueInterface")) {
this.getTranslationMessages(newExpression);
}
}
}
}
}
@Nullable
public static PhpClass getFirstClassFromFile(PhpFile phpFile) {
Collection<PhpClass> phpClasses = PsiTreeUtil.collectElementsOfType(phpFile, PhpClass.class);
return phpClasses.size() == 0 ? null : phpClasses.iterator().next();
}
public void processNextMethodReference(Method method, List<MethodReference> medRefCollection, List<MethodReference> factoryReferences) {
for(PhpReturn phpReturn: PsiTreeUtil.collectElementsOfType(method, PhpReturn.class)) {
PsiElement child = phpReturn.getFirstPsiChild();
processUpChainingMethods(child, medRefCollection, factoryReferences, true);
}
}
@Nullable
public static PhpClass getFirstClassFromFile(PhpFile phpFile) {
Collection<PhpClass> phpClasses = PsiTreeUtil.collectElementsOfType(phpFile, PhpClass.class);
return phpClasses.size() == 0 ? null : phpClasses.iterator().next();
}
/**
* Finds form name by "getName" method
*
* Symfony < 2.8
* 'foo_bar'
*
* Symfony 2.8
* "$this->getName()" -> "$this->getBlockPrefix()" -> return 'datetime';
* "UserProfileType" => "user_profile" and namespace removal
*
* Symfony 3.0
* Use class name: Foo\Class
*
*/
@Nullable
public static String getFormNameOfPhpClass(@NotNull PhpClass phpClass) {
Method method = phpClass.findOwnMethodByName("getName");
// @TODO: think of interface switches
// method not found so use class fqn
if(method == null) {
return StringUtils.stripStart(phpClass.getFQN(), "\\");
}
for (PhpReturn phpReturn : PsiTreeUtil.collectElementsOfType(method, PhpReturn.class)) {
PhpPsiElement firstPsiChild = phpReturn.getFirstPsiChild();
// $this->getBlockPrefix()
if(firstPsiChild instanceof MethodReference) {
PhpExpression classReference = ((MethodReference) firstPsiChild).getClassReference();
if(classReference != null && "this".equals(classReference.getName())) {
String name = firstPsiChild.getName();
if(name != null && "getBlockPrefix".equals(name)) {
if(phpClass.findOwnMethodByName("getBlockPrefix") != null) {
return PhpElementsUtil.getMethodReturnAsString(phpClass, name);
} else {
// method has no custom overwrite; rebuild expression here:
// FooBarType -> foo_bar
String className = phpClass.getName();
// strip Type and type
if(className.toLowerCase().endsWith("type") && className.length() > 4) {
className = className.substring(0, className.length() - 4);
}
return fr.adrienbrault.idea.symfony2plugin.util.StringUtils.underscore(className);
}
}
}
continue;
}
// string value fallback
String stringValue = PhpElementsUtil.getStringValue(firstPsiChild);
if(stringValue != null) {
return stringValue;
}
}
return null;
}