Search in sources :

Example 1 with PhpThrowExpression

use of com.kalessil.phpStorm.phpInspectionsEA.openApi.elements.PhpThrowExpression in project phpinspectionsea by kalessil.

the class ThrowRawExceptionInspector method buildVisitor.

@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    return new BasePhpElementVisitor() {

        @Override
        public void visitPhpThrowExpression(@NotNull PhpThrowExpression expression) {
            final PsiElement argument = expression.getArgument();
            if (argument instanceof NewExpression) {
                final NewExpression newExpression = (NewExpression) argument;
                final ClassReference classReference = newExpression.getClassReference();
                final String classFqn = classReference == null ? null : classReference.getFQN();
                if (classFqn != null) {
                    if (classFqn.equals("\\Exception")) {
                        holder.registerProblem(classReference, MessagesPresentationUtil.prefixWithEa(messageRawException), new TheLocalFix());
                    } else if (REPORT_MISSING_ARGUMENTS && newExpression.getParameters().length == 0) {
                        final PsiElement resolved = OpenapiResolveUtil.resolveReference(classReference);
                        if (resolved instanceof PhpClass && this.isTarget((PhpClass) resolved)) {
                            holder.registerProblem(newExpression, MessagesPresentationUtil.prefixWithEa(messageNoArguments));
                        }
                    }
                }
            }
        }

        private boolean isTarget(@NotNull PhpClass clazz) {
            final Method constructor = clazz.getConstructor();
            return constructor != null && constructor.getParameters().length == 3 && clazz.findOwnFieldByName("message", false) == null;
        }
    };
}
Also used : BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) NewExpression(com.jetbrains.php.lang.psi.elements.NewExpression) PhpClass(com.jetbrains.php.lang.psi.elements.PhpClass) PhpThrowExpression(com.kalessil.phpStorm.phpInspectionsEA.openApi.elements.PhpThrowExpression) ClassReference(com.jetbrains.php.lang.psi.elements.ClassReference) Method(com.jetbrains.php.lang.psi.elements.Method) NotNull(org.jetbrains.annotations.NotNull) PsiElement(com.intellij.psi.PsiElement) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with PhpThrowExpression

use of com.kalessil.phpStorm.phpInspectionsEA.openApi.elements.PhpThrowExpression in project phpinspectionsea by kalessil.

the class OneTimeUseVariablesInspector method buildVisitor.

@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    return new BasePhpElementVisitor() {

        void checkOneTimeUse(@NotNull PhpPsiElement construct, @NotNull Variable argument) {
            final String variableName = argument.getName();
            final PsiElement previous = construct.getPrevPsiSibling();
            /* verify preceding expression (assignment needed) */
            if (null != previous && OpenapiTypesUtil.isAssignment(previous.getFirstChild())) {
                final AssignmentExpression assign = (AssignmentExpression) previous.getFirstChild();
                /* ensure variables are the same */
                final PhpPsiElement assignVariable = assign.getVariable();
                final PsiElement assignValue = ExpressionSemanticUtil.getExpressionTroughParenthesis(assign.getValue());
                if (null != assignValue && assignVariable instanceof Variable) {
                    final String assignVariableName = assignVariable.getName();
                    if (assignVariableName == null || !assignVariableName.equals(variableName)) {
                        return;
                    }
                    /* check if variable as a function/use(...) parameter by reference */
                    final Function function = ExpressionSemanticUtil.getScope(construct);
                    if (null != function) {
                        for (final Parameter param : function.getParameters()) {
                            if (param.isPassByRef() && param.getName().equals(variableName)) {
                                return;
                            }
                        }
                        final List<Variable> useList = ExpressionSemanticUtil.getUseListVariables(function);
                        if (useList != null && !useList.isEmpty()) {
                            for (final Variable param : useList) {
                                if (param.getName().equals(variableName)) {
                                    /* detect parameters by reference in use clause */
                                    PsiElement ampersandCandidate = param.getPrevSibling();
                                    if (ampersandCandidate instanceof PsiWhiteSpace) {
                                        ampersandCandidate = ampersandCandidate.getPrevSibling();
                                    }
                                    if (OpenapiTypesUtil.is(ampersandCandidate, PhpTokenTypes.opBIT_AND)) {
                                        return;
                                    }
                                }
                            }
                            useList.clear();
                        }
                    }
                    /* too long return/throw statements can be decoupled as a variable */
                    if (!ALLOW_LONG_STATEMENTS && assign.getText().length() > 80) {
                        return;
                    }
                    /* heavy part, find usage inside function/method to analyze multiple writes */
                    final PhpScopeHolder parentScope = ExpressionSemanticUtil.getScope(assign);
                    if (null != parentScope) {
                        int countWrites = 0;
                        int countReads = 0;
                        for (final PhpAccessVariableInstruction oneCase : OpenapiControlFlowUtil.getFollowingVariableAccessInstructions(parentScope.getControlFlow().getEntryPoint(), variableName)) {
                            final boolean isWrite = oneCase.getAccess().isWrite();
                            if (isWrite) {
                                /* false-positives: type specification */
                                final PsiElement context = oneCase.getAnchor().getParent();
                                if (OpenapiTypesUtil.isAssignment(context)) {
                                    final boolean typeAnnotated = this.isTypeAnnotated((PhpPsiElement) context.getParent(), variableName);
                                    if (typeAnnotated) {
                                        return;
                                    }
                                }
                            }
                            countWrites += isWrite ? 1 : 0;
                            countReads += isWrite ? 0 : 1;
                            if (countWrites > 1 || countReads > 1) {
                                return;
                            }
                        }
                    }
                    if (!(assignValue instanceof NewExpression) || PhpLanguageLevel.get(holder.getProject()).atLeast(PhpLanguageLevel.PHP540)) {
                        holder.registerProblem(assignVariable, MessagesPresentationUtil.prefixWithEa(messagePattern.replace("%v%", variableName)), new TheLocalFix(holder.getProject(), assign.getParent(), argument, assignValue));
                    }
                }
            }
        }

        @Override
        public void visitPhpReturn(@NotNull PhpReturn returnStatement) {
            if (ANALYZE_RETURN_STATEMENTS) {
                /* if function returning reference, do not inspect returns */
                final Function callable = ExpressionSemanticUtil.getScope(returnStatement);
                final PsiElement nameNode = NamedElementUtil.getNameIdentifier(callable);
                if (null != callable && null != nameNode) {
                    /* is defined like returning reference */
                    PsiElement referenceCandidate = nameNode.getPrevSibling();
                    if (referenceCandidate instanceof PsiWhiteSpace) {
                        referenceCandidate = referenceCandidate.getPrevSibling();
                    }
                    if (OpenapiTypesUtil.is(referenceCandidate, PhpTokenTypes.opBIT_AND)) {
                        return;
                    }
                }
                /* regular function, check one-time use variables */
                final PsiElement argument = ExpressionSemanticUtil.getExpressionTroughParenthesis(returnStatement.getArgument());
                if (argument instanceof PhpPsiElement) {
                    final Variable variable = this.getVariable((PhpPsiElement) argument);
                    if (null != variable) {
                        checkOneTimeUse(returnStatement, variable);
                    }
                }
            }
        }

        @Override
        public void visitPhpMultiassignmentExpression(@NotNull MultiassignmentExpression multiassignmentExpression) {
            if (ANALYZE_ARRAY_DESTRUCTURING) {
                final PsiElement firstChild = multiassignmentExpression.getFirstChild();
                final IElementType nodeType = null == firstChild ? null : firstChild.getNode().getElementType();
                if (null != nodeType && (PhpTokenTypes.kwLIST == nodeType || PhpTokenTypes.chLBRACKET == nodeType)) {
                    final Variable variable = this.getVariable(multiassignmentExpression.getValue());
                    final PsiElement parent = multiassignmentExpression.getParent();
                    if (null != variable && OpenapiTypesUtil.isStatementImpl(parent)) {
                        checkOneTimeUse((PhpPsiElement) parent, variable);
                    }
                }
            }
        }

        /* TODO: once got bored, add foreach source pattern here =) I'm naive but nevertheless ^_^ */
        @Override
        public void visitPhpThrowExpression(@NotNull PhpThrowExpression expression) {
            if (ANALYZE_THROW_STATEMENTS) {
                final PsiElement argument = ExpressionSemanticUtil.getExpressionTroughParenthesis(expression.getArgument());
                if (argument instanceof PhpPsiElement) {
                    final Variable variable = this.getVariable((PhpPsiElement) argument);
                    if (null != variable) {
                        checkOneTimeUse(expression.getExpression(), variable);
                    }
                }
            }
        }

        @Nullable
        private Variable getVariable(@Nullable PhpPsiElement expression) {
            if (expression != null) {
                if (expression instanceof Variable) {
                    return (Variable) expression;
                } else if (expression instanceof MemberReference) {
                    final MemberReference reference = (MemberReference) expression;
                    final PsiElement candidate = reference.getFirstChild();
                    if (candidate instanceof Variable) {
                        final PsiElement operator = OpenapiPsiSearchUtil.findResolutionOperator(reference);
                        if (OpenapiTypesUtil.is(operator, PhpTokenTypes.ARROW)) {
                            return (Variable) candidate;
                        }
                    }
                } else if (OpenapiTypesUtil.isPhpExpressionImpl(expression)) {
                    /* instanceof passes child classes as well, what isn't correct */
                    return getVariable(expression.getFirstPsiChild());
                }
            }
            return null;
        }

        private boolean isTypeAnnotated(@NotNull PhpPsiElement current, @NotNull String variableName) {
            boolean result = false;
            final PsiElement phpdocCandidate = current.getPrevPsiSibling();
            if (phpdocCandidate instanceof PhpDocComment) {
                final PhpDocTag[] hints = ((PhpDocComment) phpdocCandidate).getTagElementsByName("@var");
                if (hints.length == 1) {
                    final PhpDocVariable specifiedVariable = PsiTreeUtil.findChildOfType(hints[0], PhpDocVariable.class);
                    result = specifiedVariable != null && specifiedVariable.getName().equals(variableName);
                }
            }
            return result;
        }
    };
}
Also used : PhpDocVariable(com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocVariable) NotNull(org.jetbrains.annotations.NotNull) PhpDocTag(com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag) BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) PhpScopeHolder(com.jetbrains.php.codeInsight.PhpScopeHolder) PhpThrowExpression(com.kalessil.phpStorm.phpInspectionsEA.openApi.elements.PhpThrowExpression) PhpAccessVariableInstruction(com.jetbrains.php.codeInsight.controlFlow.instructions.PhpAccessVariableInstruction) IElementType(com.intellij.psi.tree.IElementType) PhpDocComment(com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment) PhpDocVariable(com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocVariable) Nullable(org.jetbrains.annotations.Nullable) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

BasePhpElementVisitor (com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor)2 PhpThrowExpression (com.kalessil.phpStorm.phpInspectionsEA.openApi.elements.PhpThrowExpression)2 NotNull (org.jetbrains.annotations.NotNull)2 PsiElement (com.intellij.psi.PsiElement)1 IElementType (com.intellij.psi.tree.IElementType)1 PhpScopeHolder (com.jetbrains.php.codeInsight.PhpScopeHolder)1 PhpAccessVariableInstruction (com.jetbrains.php.codeInsight.controlFlow.instructions.PhpAccessVariableInstruction)1 PhpDocComment (com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocComment)1 PhpDocVariable (com.jetbrains.php.lang.documentation.phpdoc.psi.PhpDocVariable)1 PhpDocTag (com.jetbrains.php.lang.documentation.phpdoc.psi.tags.PhpDocTag)1 ClassReference (com.jetbrains.php.lang.psi.elements.ClassReference)1 Method (com.jetbrains.php.lang.psi.elements.Method)1 NewExpression (com.jetbrains.php.lang.psi.elements.NewExpression)1 PhpClass (com.jetbrains.php.lang.psi.elements.PhpClass)1 Nullable (org.jetbrains.annotations.Nullable)1