com.intellij.psi.PsiElement Java Examples

The following examples show how to use com.intellij.psi.PsiElement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractPsiElementNavigationHandler.java    From NutzCodeInsight with Apache License 2.0 6 votes vote down vote up
@Override
public void navigate(MouseEvent mouseEvent, PsiElement psiElement) {
    if (canNavigate(psiElement)) {
        final Project project = psiElement.getProject();
        final List<PsiElement> psiElements = findReferences(psiElement);
        if (psiElements.size() == 1) {
            FileEditorManager.getInstance(project).openFile(PsiUtil.getVirtualFile(psiElements.get(0)), true);
        } else if (psiElements.size() > 1) {
            NavigationUtil.getPsiElementPopup(psiElements.toArray(new PsiElement[0]), title).show(new RelativePoint(mouseEvent));
        } else {
            if (Objects.isNull(psiElements) || psiElements.size() <= 0) {
                Messages.showErrorDialog("没有找到这个调用的方法,请检查!", "错误提示");
            }
        }
    }
}
 
Example #2
Source File: PhpArrayCallbackGotoCompletion.java    From idea-php-toolbox with MIT License 6 votes vote down vote up
/**
 * [$this, '']
 * array($this, '')
 */
@NotNull
@Override
public PsiElementPattern.Capture<PsiElement> getPattern() {
    return PlatformPatterns.psiElement().withParent(
        PlatformPatterns.psiElement(StringLiteralExpression.class).withParent(
            PlatformPatterns.psiElement().withElementType(PhpElementTypes.ARRAY_VALUE).afterLeafSkipping(
                PlatformPatterns.psiElement(PsiWhiteSpace.class),
                PlatformPatterns.psiElement().withText(",")
            ).afterSiblingSkipping(
                PlatformPatterns.psiElement(PsiWhiteSpace.class),
                PlatformPatterns.psiElement().withElementType(PhpElementTypes.ARRAY_VALUE).withFirstNonWhitespaceChild(
                    PlatformPatterns.psiElement(Variable.class)
                ).afterLeafSkipping(
                    PlatformPatterns.psiElement(PsiWhiteSpace.class),
                    PlatformPatterns.psiElement().withText(PlatformPatterns.string().oneOf("[", "("))
                )
            )
        )
    );
}
 
Example #3
Source File: TranslationReferenceTest.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
public void testReferenceCanResolveDefinition() {
    PsiFile file = myFixture.configureByText(PhpFileType.INSTANCE, "<?php \n" +
            "\"LLL:EXT:foo/sample.xlf:sys_<caret>language.language_isocode.ab\";");

    PsiElement elementAtCaret = file.findElementAt(myFixture.getCaretOffset()).getParent();
    PsiReference[] references = elementAtCaret.getReferences();
    for (PsiReference reference : references) {
        if (reference instanceof TranslationReference) {
            ResolveResult[] resolveResults = ((TranslationReference) reference).multiResolve(false);
            for (ResolveResult resolveResult : resolveResults) {
                assertInstanceOf(resolveResult.getElement(), XmlAttributeValue.class);

                return;
            }
        }
    }

    fail("TranslationReference could not be resolved");
}
 
Example #4
Source File: CSharpReferenceExpressionImplUtil.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Nullable
public static CSharpCallArgumentListOwner findCallArgumentListOwner(ResolveToKind kind, CSharpReferenceExpression referenceExpression)
{
	PsiElement parent = referenceExpression.getParent();

	CSharpCallArgumentListOwner p = null;
	if(CSharpReferenceExpressionImplUtil.isConstructorKind(kind) || kind == ResolveToKind.PARAMETER)
	{
		p = PsiTreeUtil.getParentOfType(referenceExpression, CSharpCallArgumentListOwner.class);
	}
	else if(parent instanceof CSharpCallArgumentListOwner)
	{
		p = (CSharpCallArgumentListOwner) parent;
	}
	return p;
}
 
Example #5
Source File: OverrideUtil.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static Collection<PsiElement> filterOverrideElements(@Nonnull PsiScopeProcessor processor,
		@Nonnull PsiElement scopeElement,
		@Nonnull Collection<PsiElement> psiElements,
		@Nonnull OverrideProcessor overrideProcessor)
{
	if(psiElements.size() == 0)
	{
		return psiElements;
	}

	if(!ExecuteTargetUtil.canProcess(processor, ExecuteTarget.ELEMENT_GROUP, ExecuteTarget.EVENT, ExecuteTarget.PROPERTY))
	{
		return CSharpResolveUtil.mergeGroupsToIterable(psiElements);
	}

	List<PsiElement> elements = CSharpResolveUtil.mergeGroupsToIterable(psiElements);

	return filterOverrideElements(scopeElement, elements, overrideProcessor);
}
 
Example #6
Source File: HighlightManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void addOccurrenceHighlights(@Nonnull Editor editor,
                                    @Nonnull PsiElement[] elements,
                                    @Nonnull TextAttributes attributes,
                                    boolean hideByTextChange,
                                    Collection<RangeHighlighter> outHighlighters) {
  if (elements.length == 0) return;
  int flags = HIDE_BY_ESCAPE;
  if (hideByTextChange) {
    flags |= HIDE_BY_TEXT_CHANGE;
  }

  Color scrollmarkColor = getScrollMarkColor(attributes);
  if (editor instanceof EditorWindow) {
    editor = ((EditorWindow)editor).getDelegate();
  }

  for (PsiElement element : elements) {
    TextRange range = element.getTextRange();
    range = InjectedLanguageManager.getInstance(myProject).injectedToHost(element, range);
    addOccurrenceHighlight(editor, range.getStartOffset(), range.getEndOffset(), attributes, flags, outHighlighters, scrollmarkColor);
  }
}
 
Example #7
Source File: HaxeTypeResolver.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
static private void checkMethod(PsiElement element, HaxeExpressionEvaluatorContext context) {
  if (!(element instanceof HaxeMethod)) return;
  final HaxeTypeTag typeTag = UsefulPsiTreeUtil.getChild(element, HaxeTypeTag.class);
  ResultHolder expectedType = SpecificTypeReference.getDynamic(element).createHolder();
  if (typeTag == null) {
    final List<ReturnInfo> infos = context.getReturnInfos();
    if (!infos.isEmpty()) {
      expectedType = infos.get(0).type;
    }
  } else {
    expectedType = getTypeFromTypeTag(typeTag, element);
  }

  if (expectedType == null) return;
  for (ReturnInfo retinfo : context.getReturnInfos()) {
    if (expectedType.canAssign(retinfo.type)) continue;
    context.addError(
      retinfo.element,
      "Can't return " + retinfo.type + ", expected " + expectedType.toStringWithoutConstant()
    );
  }
}
 
Example #8
Source File: TwigPattern.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
public static ElementPattern<PsiElement> getSetVariablePattern() {

        // {% set count1 = "var" %}

        //noinspection unchecked
        return PlatformPatterns
            .psiElement(TwigTokenTypes.IDENTIFIER)
            .afterLeafSkipping(
                PlatformPatterns.or(
                    PlatformPatterns.psiElement(PsiWhiteSpace.class),
                    PlatformPatterns.psiElement(TwigTokenTypes.WHITE_SPACE)
                ),
                PlatformPatterns.psiElement(TwigTokenTypes.EQ)
            )
            .withParent(
                PlatformPatterns.psiElement(TwigElementTypes.SET_TAG)
            )
            .withLanguage(TwigLanguage.INSTANCE);
    }
 
Example #9
Source File: DefaultChooseByNameItemProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static boolean filterElements(@Nonnull ChooseByNameViewModel base,
                                      @Nonnull ProgressIndicator indicator,
                                      @Nullable PsiElement context,
                                      @Nullable Supplier<String[]> allNamesProducer,
                                      @Nonnull Processor<FoundItemDescriptor<?>> consumer,
                                      @Nonnull FindSymbolParameters parameters) {
  boolean everywhere = parameters.isSearchInLibraries();
  String pattern = parameters.getCompletePattern();
  if (base.getProject() != null) {
    base.getProject().putUserData(ChooseByNamePopup.CURRENT_SEARCH_PATTERN, pattern);
  }

  String namePattern = getNamePattern(base, pattern);
  boolean preferStartMatches = !pattern.startsWith("*");

  List<MatchResult> namesList = getSortedNamesForAllWildcards(base, parameters, indicator, allNamesProducer, namePattern, preferStartMatches);

  indicator.checkCanceled();

  return processByNames(base, everywhere, indicator, context, consumer, preferStartMatches, namesList, parameters);
}
 
Example #10
Source File: BuckTestAtCursorAction.java    From buck with Apache License 2.0 6 votes vote down vote up
private void findTestAndDo(AnActionEvent anActionEvent, BiConsumer<PsiClass, PsiMethod> action) {
  PsiElement psiElement = anActionEvent.getData(CommonDataKeys.PSI_ELEMENT);
  PsiFile psiFile = anActionEvent.getData(LangDataKeys.PSI_FILE);
  if (psiElement == null) {
    Editor editor = anActionEvent.getData(CommonDataKeys.EDITOR);
    if (editor != null && psiFile != null) {
      psiElement = psiFile.findElementAt(editor.getCaretModel().getOffset());
    }
  }
  if (psiFile == null && psiElement != null) {
    psiFile = psiElement.getContainingFile();
  }
  if (psiElement != null) {
    PsiElement testElement = findNearestTestElement(psiFile, psiElement);
    if (testElement instanceof PsiClass) {
      PsiClass psiClass = (PsiClass) testElement;
      action.accept(psiClass, null);
      return;
    } else if (testElement instanceof PsiMethod) {
      PsiMethod psiMethod = (PsiMethod) testElement;
      action.accept(psiMethod.getContainingClass(), psiMethod);
      return;
    }
  }
  action.accept(null, null);
}
 
Example #11
Source File: ParameterInfoController.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static <E extends PsiElement> E findArgumentList(PsiFile file, int offset, int lbraceOffset) {
  if (file == null) return null;
  ParameterInfoHandler[] handlers = ShowParameterInfoHandler.getHandlers(file.getProject(), PsiUtilCore.getLanguageAtOffset(file, offset), file.getViewProvider().getBaseLanguage());

  if (handlers != null) {
    for (ParameterInfoHandler handler : handlers) {
      if (handler instanceof ParameterInfoHandlerWithTabActionSupport) {
        final ParameterInfoHandlerWithTabActionSupport parameterInfoHandler2 = (ParameterInfoHandlerWithTabActionSupport)handler;

        // please don't remove typecast in the following line; it's required to compile the code under old JDK 6 versions
        final E e = ParameterInfoUtils.findArgumentList(file, offset, lbraceOffset, parameterInfoHandler2);
        if (e != null) return e;
      }
    }
  }

  return null;
}
 
Example #12
Source File: PhpElementsUtil.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
@Nullable
public static String extractArrayIndexFromValue(PsiElement element) {
    PsiElement arrayElement;
    if (element.getParent() instanceof StringLiteralExpression) {
        arrayElement = element.getParent().getParent().getParent();
    } else {
        arrayElement = element.getParent().getParent();
    }

    if (arrayElement instanceof ArrayHashElement) {
        ArrayHashElement arrayHashElement = (ArrayHashElement) arrayElement;
        return extractIndexFromArrayHash(arrayHashElement);
    }

    return null;
}
 
Example #13
Source File: Trees.java    From antlr4-intellij-adaptor with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/** Find smallest subtree of t enclosing range startCharIndex..stopCharIndex
 *  inclusively using postorder traversal.  Recursive depth-first-search.
 */
public static PsiElement getRootOfSubtreeEnclosingRegion(PsiElement t,
                                                         int startCharIndex, // inclusive
                                                         int stopCharIndex)  // inclusive
{
	for (PsiElement c : t.getChildren()) {
		PsiElement sub = getRootOfSubtreeEnclosingRegion(c, startCharIndex, stopCharIndex);
		if ( sub!=null ) return sub;
	}
	IElementType elementType = t.getNode().getElementType();
	if ( elementType instanceof RuleIElementType ) {
		TextRange r = t.getNode().getTextRange();
		// is range fully contained in t?  Note: jetbrains uses exclusive right end (use < not <=)
		if ( startCharIndex>=r.getStartOffset() && stopCharIndex<r.getEndOffset() ) {
			return t;
		}
	}
	return null;
}
 
Example #14
Source File: CamelIdeaUtils.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * @return Resolve the bean {@link PsiClass} from the specified element or return null
 */
public PsiClass getBean(PsiElement element) {
    return enabledExtensions.stream()
        .map(c -> c.getBeanClass(element))
        .filter(Objects::nonNull)
        .findFirst().orElse(null);
}
 
Example #15
Source File: Identikit.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
static Pair<ByAnchor, PsiElement> withAnchor(@Nonnull PsiElement element, @Nonnull Language fileLanguage) {
  PsiUtilCore.ensureValid(element);
  if (element.isPhysical()) {
    for (SmartPointerAnchorProvider provider : SmartPointerAnchorProvider.EP_NAME.getExtensionList()) {
      PsiElement anchor = provider.getAnchor(element);
      if (anchor != null && anchor.isPhysical() && provider.restoreElement(anchor) == element) {
        ByAnchor anchorKit = new ByAnchor(fromPsi(element, fileLanguage), fromPsi(anchor, fileLanguage), provider);
        return Pair.create(ourAnchorInterner.intern(anchorKit), anchor);
      }
    }
  }
  return null;
}
 
Example #16
Source File: MsilVariableAsCSharpVariable.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
public MsilVariableAsCSharpVariable(PsiElement parent, CSharpModifier[] modifiers, DotNetVariable variable)
{
	super(parent, variable);
	setNavigationElement(variable);
	myModifierList = createModifierList(modifiers, variable);
}
 
Example #17
Source File: QuickEditAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
public QuickEditHandler invokeImpl(@Nonnull final Project project, final Editor editor, PsiFile file) throws IncorrectOperationException {
  int offset = editor.getCaretModel().getOffset();
  Pair<PsiElement, TextRange> pair = ObjectUtils.assertNotNull(getRangePair(file, editor));

  PsiFile injectedFile = (PsiFile)pair.first;
  QuickEditHandler handler = getHandler(project, injectedFile, editor, file);

  if (!ApplicationManager.getApplication().isUnitTestMode()) {
    DocumentWindow documentWindow = InjectedLanguageUtil.getDocumentWindow(injectedFile);
    if (documentWindow != null) {
      handler.navigate(InjectedLanguageUtil.hostToInjectedUnescaped(documentWindow, offset));
    }
  }
  return handler;
}
 
Example #18
Source File: CustomRenameHandlerTest.java    From Intellij-Plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testShouldRenameSpecStepElement() throws Exception {
    PsiElement element = mock(SpecStepImpl.class);

    when(virtualFile.getFileType()).thenReturn(SpecFileType.INSTANCE);
    when(dataContext.getData(CommonDataKeys.PSI_ELEMENT.getName())).thenReturn(element);
    when(dataContext.getData(CommonDataKeys.VIRTUAL_FILE.getName())).thenReturn(virtualFile);
    when(dataContext.getData(CommonDataKeys.EDITOR.getName())).thenReturn(editor);
    when(dataContext.getData(CommonDataKeys.PROJECT.getName())).thenReturn(project);

    assertTrue("Should rename the spec step. Expected: true, Actual: false", new CustomRenameHandler().isAvailableOnDataContext(dataContext));
}
 
Example #19
Source File: RTMergerTreeStructureProvider.java    From react-templates-plugin with MIT License 5 votes vote down vote up
private static Collection<BasePsiNode<? extends PsiElement>> findFormsIn(Collection<AbstractTreeNode> children, List<PsiFile> forms) {
    if (children.isEmpty() || forms.isEmpty()) return Collections.emptyList();
    List<BasePsiNode<? extends PsiElement>> result = new ArrayList<BasePsiNode<? extends PsiElement>>();
    Set<PsiFile> psiFiles = new HashSet<PsiFile>(forms);
    for (final AbstractTreeNode child : children) {
        if (child instanceof BasePsiNode) {
            //noinspection unchecked
            BasePsiNode<? extends PsiElement> treeNode = (BasePsiNode<? extends PsiElement>) child;
            //noinspection SuspiciousMethodCalls
            if (psiFiles.contains(treeNode.getValue())) result.add(treeNode);
        }
    }
    return result;
}
 
Example #20
Source File: DefaultPackageQualifiedNameProvider.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public PsiElement adjustElementToCopy(PsiElement element) {
  if (element instanceof PsiPackage) {
    return element;
  }
  if (element instanceof PsiDirectory) {
    final PsiPackage psiPackage = PsiPackageManager.getInstance(element.getProject()).findAnyPackage((PsiDirectory)element);
    if (psiPackage != null) {
      return psiPackage;
    }
  }
  return null;
}
 
Example #21
Source File: DartSyntax.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Check if an element is a declaration of "main".
 *
 * @return true if the given element is a main declaration, false otherwise
 */
public static boolean isMainFunctionDeclaration(@Nullable PsiElement element) {
  if (!(element instanceof DartFunctionDeclarationWithBodyOrNative)) {
    return false;
  }

  final String functionName = ((DartFunctionDeclarationWithBodyOrNative)element).getComponentName().getId().getText();
  return Objects.equals(functionName, "main");
}
 
Example #22
Source File: TomcatRunConfigurationProducer.java    From SmartTomcat with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean setupConfigurationFromContext(@NotNull TomcatRunConfiguration configuration, @NotNull ConfigurationContext context, @NotNull Ref<PsiElement> sourceElement) {

    boolean result = isConfigurationFromContext(configuration, context);

    if (result) {
        List<TomcatInfo> tomcatInfos = TomcatInfoConfigs.getInstance().getTomcatInfos();
        if (tomcatInfos != null && tomcatInfos.size() > 0) {
            TomcatInfo tomcatInfo = tomcatInfos.get(0);
            configuration.setTomcatInfo(tomcatInfo);
        } else  {
            throw new RuntimeException("Not found any Tomcat Server, please add Tomcat Server first.");
        }

        VirtualFile virtualFile = context.getLocation().getVirtualFile();
        Module module = context.getModule();
        configuration.setName(module.getName());
        configuration.setDocBase(virtualFile.getCanonicalPath());
        configuration.setContextPath("/" + module.getName());
        configuration.setModuleName(module.getName());

        final RunnerAndConfigurationSettings settings =
                RunManager.getInstance(context.getProject()).createConfiguration(configuration, getConfigurationFactory());
        settings.setName(module.getName() + " in SmartTomcat");
    }
    return result;
}
 
Example #23
Source File: DartSyntaxTest.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void shouldFindEnclosingFunctionCallPattern() throws Exception {
  run(() -> {
    final PsiElement helloElt = setUpDartElement("main() { test(\"hello\"); }", "hello", LeafPsiElement.class);

    final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(helloElt, Pattern.compile("t.*t"));
    assertNotNull("findEnclosingFunctionCall() didn't find enclosing function call", call);
  });
}
 
Example #24
Source File: UppercaseStatePropInspection.java    From litho with Apache License 2.0 5 votes vote down vote up
private static ProblemDescriptor createWarning(
    PsiElement element, InspectionManager manager, boolean isOnTheFly) {
  return manager.createProblemDescriptor(
      element,
      "Should not be capitalized: " + element.getText(),
      true /* show tooltip */,
      ProblemHighlightType.ERROR,
      isOnTheFly);
}
 
Example #25
Source File: ConfigCompletionGoto.java    From idea-php-drupal-symfony2-bridge with MIT License 5 votes vote down vote up
@NotNull
@Override
public Collection<PsiElement> getPsiTargets(PsiElement psiElement) {

    PsiElement element = psiElement.getParent();
    if(!(element instanceof StringLiteralExpression)) {
        return Collections.emptyList();
    }

    final String contents = ((StringLiteralExpression) element).getContents();
    if(StringUtils.isBlank(contents)) {
        return Collections.emptyList();
    }

    final Collection<PsiElement> psiElements = new ArrayList<>();
    FileBasedIndex.getInstance().getFilesWithKey(ConfigSchemaIndex.KEY, new HashSet<>(Collections.singletonList(contents)), virtualFile -> {

        PsiFile psiFile = PsiManager.getInstance(getProject()).findFile(virtualFile);
        if(psiFile == null) {
            return true;
        }

        YAMLDocument yamlDocument = PsiTreeUtil.getChildOfType(psiFile, YAMLDocument.class);
        if(yamlDocument == null) {
            return true;
        }

        for(YAMLKeyValue yamlKeyValue: PsiTreeUtil.getChildrenOfTypeAsList(yamlDocument, YAMLKeyValue.class)) {
            String keyText = PsiElementUtils.trimQuote(yamlKeyValue.getKeyText());
            if(StringUtils.isNotBlank(keyText) && keyText.equals(contents)) {
                psiElements.add(yamlKeyValue);
            }
        }

        return true;
    }, GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(getProject()), YAMLFileType.YML));

    return psiElements;
}
 
Example #26
Source File: CustomOptionReferenceTest.java    From protobuf-jetbrains-plugin with Apache License 2.0 5 votes vote down vote up
public void testImportedImportedCustomOptionReference() {
    myFixture.configureByFiles(
            "reference/options/custom/SimpleExtensionField.proto",
            "reference/options/custom/ImportedExtension.proto"
    );
    PsiReference reference = myFixture.getReferenceAtCaretPositionWithAssertion(
            "reference/options/custom/ImportedImportedExtension.proto"
    );
    PsiElement target = reference.resolve();
    Assert.assertNotNull(target);
    Assert.assertTrue(target instanceof FieldNode);
    FieldNode field = (FieldNode) target;
    Assert.assertEquals("bar", field.getFieldName());
    Assert.assertTrue(field.getParent() instanceof ExtendEntryNode);
}
 
Example #27
Source File: CSharpLightLikeMethodDeclarationBuilder.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Nullable
@Override
public String getPresentableParentQName()
{
	PsiElement parent = getParent();
	if(parent instanceof DotNetQualifiedElement)
	{
		return ((DotNetQualifiedElement) parent).getPresentableQName();
	}
	return myParentQName;
}
 
Example #28
Source File: PhpClassServiceGotoDeclarationHandler.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Nullable
@Override
public PsiElement[] getGotoDeclarationTargets(PsiElement psiElement, int offset, Editor editor) {
    if(!Symfony2ProjectComponent.isEnabled(psiElement) || !PhpElementsUtil.getClassNamePattern().accepts(psiElement)) {
        return new PsiElement[0];
    }

    return ServiceIndexUtil.findServiceDefinitions((PhpClass) psiElement.getContext());
}
 
Example #29
Source File: ResolveInFunctorTest.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
public void testRml_FileInclude() {
    configureCode("A.re", "module Make = (M:I) => { let a = 3; }; include Make({})");
    configureCode("B.re", "let b = A.a<caret>;");

    PsiElement e = myFixture.getElementAtCaret();
    assertEquals("A.Make.a", ((PsiQualifiedElement) e.getParent()).getQualifiedName());
}
 
Example #30
Source File: ShopwareBoostrapInspection.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(final @NotNull ProblemsHolder holder, boolean isOnTheFly) {
    PsiFile psiFile = holder.getFile();
    if(!ShopwareProjectComponent.isValidForProject(psiFile)) {
        return super.buildVisitor(holder, isOnTheFly);
    }

    if(!"Bootstrap.php".equals(psiFile.getName())) {
        return super.buildVisitor(holder, isOnTheFly);
    }

    return new PsiElementVisitor() {
        @Override
        public void visitElement(PsiElement element) {
            if(element instanceof Method) {
                String methodName = ((Method) element).getName();
                if(INSTALL_METHODS.contains(((Method) element).getName())) {
                    if(PsiTreeUtil.collectElementsOfType(element, PhpReturn.class).size() == 0) {
                        PsiElement psiElement = PsiElementUtils.getChildrenOfType(element, PlatformPatterns.psiElement(PhpTokenTypes.IDENTIFIER).withText(methodName));
                        if(psiElement != null) {
                            holder.registerProblem(psiElement, "Shopware need return statement", ProblemHighlightType.GENERIC_ERROR);
                        }
                    }
                }

            }

            super.visitElement(element);
        }
    };
}