Search in sources :

Example 6 with MethodReference

use of com.jetbrains.php.lang.psi.elements.MethodReference in project yii2support by nvlad.

the class RequireParameterLocalQuickFix method applyFix.

@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    ParameterList parameterList = ((MethodReference) descriptor.getPsiElement()).getParameterList();
    if (parameterList == null) {
        return;
    }
    PsiElement[] parameters = parameterList.getParameters();
    if (parameters.length == 1 || parameters[1] instanceof PsiErrorElement) {
        ArrayCreationExpression params = PhpPsiElementFactory.createFromText(project, ArrayCreationExpression.class, "[]");
        if (params == null) {
            return;
        }
        if (parameters.length == 1) {
            parameterList.add(PhpPsiElementFactory.createComma(project));
        } else {
            parameterList.deleteChildRange(parameters[1], parameters[1]);
        }
        parameterList.add(params);
        parameters = parameterList.getParameters();
    }
    TemplateManager templateManager = TemplateManager.getInstance(project);
    Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
    if (editor == null) {
        return;
    }
    if (parameters[1] instanceof FunctionReference) {
        FunctionReference functionReference = (FunctionReference) parameters[1];
        if (functionReference.getName() == null || !functionReference.getName().equals("compact")) {
            return;
        }
        Template template = templateManager.createTemplate("", "");
        template.setToReformat(true);
        Boolean firstElement = functionReference.getParameters().length == 0;
        for (String variable : myVariables) {
            template.addTextSegment(firstElement ? "'" : ", '");
            String var = "$" + variable.toUpperCase() + "$";
            template.addVariable(var, "", "\"" + variable + "\"", true);
            template.addVariableSegment(var);
            template.addTextSegment("'");
            firstElement = false;
        }
        PsiElement psiElement = functionReference.getParameterList();
        if (psiElement != null) {
            editor.getCaretModel().moveToOffset(psiElement.getTextRange().getEndOffset());
            PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
            templateManager.startTemplate(editor, template);
        }
        return;
    }
    if (!(parameters[1] instanceof ArrayCreationExpression)) {
        return;
    }
    ArrayCreationExpression params = (ArrayCreationExpression) parameters[1];
    Template template = templateManager.createTemplate("", "");
    template.setToReformat(true);
    Boolean addComma = params.getHashElements().iterator().hasNext();
    Boolean newLined = false;
    PsiElement psiElement = params.getLastChild();
    while (psiElement instanceof PsiWhiteSpace || psiElement.getText().equals("]")) {
        if (psiElement instanceof PsiWhiteSpace && psiElement.getText().contains("\n")) {
            newLined = true;
        }
        psiElement = psiElement.getPrevSibling();
    }
    if (psiElement.getText().equals(",")) {
        addComma = false;
    }
    for (String variable : myVariables) {
        if (addComma) {
            template.addTextSegment(",");
        }
        template.addTextSegment((newLined ? "\n" : " "));
        String templateVariable = "$" + variable.toUpperCase() + "$";
        template.addVariable(templateVariable, "", "\"$" + variable + "\"", true);
        template.addTextSegment("'" + variable + "' => ");
        template.addVariableSegment(templateVariable);
        addComma = true;
    }
    template.addTextSegment(newLined ? "," : " ");
    editor.getCaretModel().moveToOffset(psiElement.getTextRange().getEndOffset());
    PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
    templateManager.startTemplate(editor, template);
}
Also used : ArrayCreationExpression(com.jetbrains.php.lang.psi.elements.ArrayCreationExpression) Template(com.intellij.codeInsight.template.Template) PsiErrorElement(com.intellij.psi.PsiErrorElement) TemplateManager(com.intellij.codeInsight.template.TemplateManager) ParameterList(com.jetbrains.php.lang.psi.elements.ParameterList) FunctionReference(com.jetbrains.php.lang.psi.elements.FunctionReference) MethodReference(com.jetbrains.php.lang.psi.elements.MethodReference) Editor(com.intellij.openapi.editor.Editor) PsiElement(com.intellij.psi.PsiElement) PsiWhiteSpace(com.intellij.psi.PsiWhiteSpace)

Example 7 with MethodReference

use of com.jetbrains.php.lang.psi.elements.MethodReference in project idea-php-typo3-plugin by cedricziel.

the class ControllerActionLookupElement method handleInsert.

@Override
public void handleInsert(InsertionContext context) {
    PsiElement elementAt = context.getFile().findElementAt(context.getStartOffset());
    if (elementAt != null) {
        MethodReference methodReference = PhpLangUtil.getMethodReference(elementAt);
        if (methodReference != null) {
            ParameterList parameters = methodReference.getParameterList();
            PsiElement[] children = parameters.getChildren();
            while (parameters.getFirstChild() != null) {
                parameters.getFirstChild().delete();
            }
            String shortActionName = controllerAction.getName().replace("Action", "");
            parameters.add(PhpPsiElementFactory.createPhpPsiFromText(context.getProject(), StringLiteralExpression.class, "'" + shortActionName + "'"));
            parameters.add(PhpPsiElementFactory.createComma(context.getProject()));
            String shortControllerName = controllerAction.getControllerName().replace("Controller", "");
            parameters.add(PhpPsiElementFactory.createPhpPsiFromText(context.getProject(), StringLiteralExpression.class, "'" + shortControllerName + "'"));
            parameters.add(PhpPsiElementFactory.createComma(context.getProject()));
            String extensionName = controllerAction.getExtensionName();
            parameters.add(PhpPsiElementFactory.createPhpPsiFromText(context.getProject(), StringLiteralExpression.class, "'" + extensionName + "'"));
        }
    }
    super.handleInsert(context);
}
Also used : StringLiteralExpression(com.jetbrains.php.lang.psi.elements.StringLiteralExpression) ParameterList(com.jetbrains.php.lang.psi.elements.ParameterList) MethodReference(com.jetbrains.php.lang.psi.elements.MethodReference) PsiElement(com.intellij.psi.PsiElement)

Example 8 with MethodReference

use of com.jetbrains.php.lang.psi.elements.MethodReference in project idea-php-typo3-plugin by cedricziel.

the class ObjectManagerTypeProvider method getType.

@Nullable
@Override
public PhpType getType(PsiElement psiElement) {
    if (DumbService.getInstance(psiElement.getProject()).isDumb()) {
        return null;
    }
    if (!(psiElement instanceof MethodReference) || !PhpElementsUtil.isMethodWithFirstStringOrFieldReference(psiElement, "get")) {
        return null;
    }
    MethodReference methodReference = (MethodReference) psiElement;
    if (methodReference.getParameters().length == 0) {
        return null;
    }
    PsiElement firstParam = methodReference.getParameters()[0];
    if (firstParam instanceof PhpReference) {
        PhpReference ref = (PhpReference) firstParam;
        if (ref.getText().toLowerCase().contains("::class")) {
            return new PhpType().add("#" + this.getKey() + ref.getSignature());
        }
    }
    return null;
}
Also used : PhpReference(com.jetbrains.php.lang.psi.elements.PhpReference) MethodReference(com.jetbrains.php.lang.psi.elements.MethodReference) PsiElement(com.intellij.psi.PsiElement) PhpType(com.jetbrains.php.lang.psi.resolve.types.PhpType) Nullable(org.jetbrains.annotations.Nullable)

Example 9 with MethodReference

use of com.jetbrains.php.lang.psi.elements.MethodReference in project phpinspectionsea by kalessil.

the class ChainedCallsStrategy method apply.

private static void apply(@NotNull MethodReference reference, @NotNull Map<MethodReference, String> nullTestedReferences, @NotNull ProblemsHolder holder) {
    final PsiElement operator = OpenapiPsiSearchUtil.findResolutionOperator(reference);
    if (OpenapiTypesUtil.is(operator, PhpTokenTypes.ARROW)) {
        final PsiElement base = reference.getFirstPsiChild();
        if (base instanceof FunctionReference) {
            final FunctionReference baseCall = (FunctionReference) base;
            final PhpType returnType = OpenapiResolveUtil.resolveType(baseCall, holder.getProject());
            if (returnType != null) {
                final String methodName = baseCall.getName();
                for (final String resolvedType : returnType.filterUnknown().getTypes()) {
                    final String type = Types.getType(resolvedType);
                    if (type.equals(Types.strNull) || type.equals(Types.strVoid)) {
                        boolean isNullTested = false;
                        for (final Map.Entry<MethodReference, String> knownReference : nullTestedReferences.entrySet()) {
                            final String nullTestedMethodName = knownReference.getValue();
                            if (nullTestedMethodName != null && nullTestedMethodName.equals(methodName) && OpeanapiEquivalenceUtil.areEqual(knownReference.getKey(), baseCall)) {
                                isNullTested = true;
                                break;
                            }
                        }
                        if (!isNullTested) {
                            holder.registerProblem(operator, message);
                            break;
                        }
                    }
                }
            }
        }
        /* collect null-tested references: only after main inspection! */
        final PsiElement parent = reference.getParent();
        if (parent instanceof BinaryExpression) {
            final BinaryExpression parentExpression = (BinaryExpression) parent;
            if (PhpTokenTypes.tsCOMPARE_OPS.contains(parentExpression.getOperationType())) {
                final PsiElement secondOperand = OpenapiElementsUtil.getSecondOperand(parentExpression, reference);
                if (PhpLanguageUtil.isNull(secondOperand)) {
                    nullTestedReferences.put(reference, reference.getName());
                }
            }
        } else if (ExpressionSemanticUtil.isUsedAsLogicalOperand(reference)) {
            nullTestedReferences.put(reference, reference.getName());
        }
    }
}
Also used : BinaryExpression(com.jetbrains.php.lang.psi.elements.BinaryExpression) FunctionReference(com.jetbrains.php.lang.psi.elements.FunctionReference) MethodReference(com.jetbrains.php.lang.psi.elements.MethodReference) HashMap(java.util.HashMap) Map(java.util.Map) PsiElement(com.intellij.psi.PsiElement) PhpType(com.jetbrains.php.lang.psi.resolve.types.PhpType)

Example 10 with MethodReference

use of com.jetbrains.php.lang.psi.elements.MethodReference in project phpinspectionsea by kalessil.

the class StaticInvocationViaThisInspector method buildVisitor.

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

        @Override
        public void visitPhpMethodReference(@NotNull MethodReference reference) {
            /* Basic structure validation */
            final PsiElement operator = OpenapiPsiSearchUtil.findResolutionOperator(reference);
            if (!OpenapiTypesUtil.is(operator, PhpTokenTypes.ARROW)) {
                return;
            }
            final PsiReference psiReference = reference.getReference();
            final String methodName = reference.getName();
            if (psiReference == null || methodName == null || methodName.startsWith("static")) {
                return;
            }
            /* check contexts: $this->, <expression>-> ; placed here due to performance optimization */
            final PsiElement thisCandidate = reference.getFirstChild();
            final boolean contextOfThis = thisCandidate.getText().equals("$this");
            final PsiElement objectExpression = contextOfThis ? null : reference.getFirstPsiChild();
            final boolean contextOfExpression = null != objectExpression && !(objectExpression instanceof FunctionReference);
            if (!contextOfThis && !contextOfExpression) {
                return;
            }
            /* now analyze: contexts are valid  */
            final PsiElement resolved = OpenapiResolveUtil.resolveReference(psiReference);
            if (resolved instanceof Method) {
                final Method method = (Method) resolved;
                /* non-static methods and contract interfaces must not be reported */
                if (!method.isStatic() || method.isAbstract()) {
                    return;
                }
                final PhpClass clazz = method.getContainingClass();
                if (clazz == null || clazz.isInterface()) {
                    return;
                }
                /* PHP Unit's official docs saying to use $this, follow the guidance */
                if (RESPECT_PHPUNIT_STANDARDS) {
                    final String classFqn = clazz.getFQN();
                    if (classFqn.startsWith("\\PHPUnit_Framework_") || classFqn.startsWith("\\PHPUnit\\Framework\\")) {
                        return;
                    }
                }
                /* Case 1: $this-><static method>() */
                if (contextOfThis) {
                    holder.registerProblem(thisCandidate, messageThisUsed.replace("%m%", methodName), new TheLocalFix(thisCandidate, operator));
                } else /* Case 2: <expression>-><static method>(); no chained calls; no QF - needs looking into cases */
                {
                    holder.registerProblem(reference, messageExpressionUsed.replace("%m%", methodName));
                }
            }
        }
    };
}
Also used : BasePhpElementVisitor(com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor) PhpClass(com.jetbrains.php.lang.psi.elements.PhpClass) FunctionReference(com.jetbrains.php.lang.psi.elements.FunctionReference) MethodReference(com.jetbrains.php.lang.psi.elements.MethodReference) Method(com.jetbrains.php.lang.psi.elements.Method) NotNull(org.jetbrains.annotations.NotNull) LeafPsiElement(com.intellij.psi.impl.source.tree.LeafPsiElement) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

MethodReference (com.jetbrains.php.lang.psi.elements.MethodReference)19 PsiElement (com.intellij.psi.PsiElement)15 NotNull (org.jetbrains.annotations.NotNull)9 FunctionReference (com.jetbrains.php.lang.psi.elements.FunctionReference)7 PhpType (com.jetbrains.php.lang.psi.resolve.types.PhpType)7 Project (com.intellij.openapi.project.Project)5 ParameterList (com.jetbrains.php.lang.psi.elements.ParameterList)4 StringLiteralExpression (com.jetbrains.php.lang.psi.elements.StringLiteralExpression)4 PhpElementVisitor (com.jetbrains.php.lang.psi.visitors.PhpElementVisitor)4 BasePhpElementVisitor (com.kalessil.phpStorm.phpInspectionsEA.openApi.BasePhpElementVisitor)4 ViewResolve (com.nvlad.yii2support.views.entities.ViewResolve)4 Function (com.jetbrains.php.lang.psi.elements.Function)3 ViewInfo (com.nvlad.yii2support.views.entities.ViewInfo)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Nullable (org.jetbrains.annotations.Nullable)3 ProblemsHolder (com.intellij.codeInspection.ProblemsHolder)2 ArrayCreationExpression (com.jetbrains.php.lang.psi.elements.ArrayCreationExpression)2 PhpReference (com.jetbrains.php.lang.psi.elements.PhpReference)2 HashSet (java.util.HashSet)2