com.jetbrains.php.lang.psi.elements.PhpPsiElement Java Examples

The following examples show how to use com.jetbrains.php.lang.psi.elements.PhpPsiElement. 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: AnnotationUseImporter.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
public static void insertUse(InsertionContext context, String fqnAnnotation) {
    PsiElement element = PsiUtilCore.getElementAtOffset(context.getFile(), context.getStartOffset());
    PhpPsiElement scopeForUseOperator = PhpCodeInsightUtil.findScopeForUseOperator(element);

    if(null == scopeForUseOperator) {
        return;
    }

    // PhpCodeInsightUtil.canImport:
    // copied from PhpReferenceInsertHandler; throws an error on PhpContractUtil because of "fully qualified names only"
    // but that is catch on phpstorm side already; looks fixed now so use fqn

    if(!fqnAnnotation.startsWith("\\")) {
        fqnAnnotation = "\\" + fqnAnnotation;
    }

    // this looks suitable! :)
    if(PhpCodeInsightUtil.alreadyImported(scopeForUseOperator, fqnAnnotation) == null) {
        PsiDocumentManager.getInstance(context.getProject()).commitDocument(context.getDocument());
        PhpAliasImporter.insertUseStatement(fqnAnnotation, scopeForUseOperator);
        PsiDocumentManager.getInstance(context.getProject()).doPostponedOperationsAndUnblockDocument(context.getDocument());
    }
}
 
Example #2
Source File: YiiReferenceContributor.java    From yiistorm with MIT License 6 votes vote down vote up
@Override
public void registerReferenceProviders(PsiReferenceRegistrar registrar) {
    registrar.registerReferenceProvider(StandardPatterns.instanceOf(PhpPsiElement.class), new YiiPsiReferenceProvider());
    registrar.registerReferenceProvider(
            PlatformPatterns.psiElement(PsiElement.class).withParent(isParamListInMethodWithName(".+?widget\\(.+"))
            , new WidgetCallReferenceProvider());
    //View-to-view
    registrar.registerReferenceProvider(
            PlatformPatterns.psiElement(PhpPsiElement.class)
                    .withParent(isParamListInMethodWithName(".+?render(Partial)*\\(.+"))
                    .andNot(inFile(PlatformPatterns.string().endsWith("Controller.php")))
            , new ViewRenderViewReferenceProvider());
    //Controller-to-view
    registrar.registerReferenceProvider(
            PlatformPatterns.psiElement(PhpPsiElement.class)
                    .withParent(isParamListInMethodWithName("(?sim).+?render(Partial)*\\(.+"))
                    .and(inFile(PlatformPatterns.string().endsWith("Controller.php")))
            , new ControllerRenderViewReferenceProvider());
}
 
Example #3
Source File: AnnotationInspectionUtil.java    From idea-php-annotation-plugin with MIT License 6 votes vote down vote up
@Nullable
public String getNamespace() {
    if (hasNamespace) {
        return this.namespace;
    }

    PhpPsiElement scope = PhpCodeInsightUtil.findScopeForUseOperator(psiElement);

    if (scope instanceof PhpNamespace) {
        String namespaceFqn = ((PhpNamespace) scope).getFQN();
        if (PhpLangUtil.isFqn(namespaceFqn) && !PhpLangUtil.isGlobalNamespaceFQN(namespaceFqn)) {
            hasNamespace = true;
            return this.namespace = namespaceFqn;
        }
    }

    return this.namespace = null;
}
 
Example #4
Source File: ColumnNameCompletionProvider.java    From idea-php-annotation-plugin with MIT License 6 votes vote down vote up
@Override
public void getPropertyValueCompletions(AnnotationPropertyParameter annotationPropertyParameter, AnnotationCompletionProviderParameter completionParameter) {

    String propertyName = annotationPropertyParameter.getPropertyName();
    if(propertyName == null) {
        return;
    }

    if(propertyName.equals("name") && PhpLangUtil.equalsClassNames(annotationPropertyParameter.getPhpClass().getPresentableFQN(), "Doctrine\\ORM\\Mapping\\Column")) {
        PhpDocComment phpDocComment = PsiTreeUtil.getParentOfType(annotationPropertyParameter.getElement(), PhpDocComment.class);
        if(phpDocComment != null) {
            PhpPsiElement classField = phpDocComment.getNextPsiSibling();
            if(classField != null && classField.getNode().getElementType() == PhpElementTypes.CLASS_FIELDS) {
                Field field = PsiTreeUtil.getChildOfType(classField, Field.class);
                if(field != null) {
                    String name = field.getName();
                    if(StringUtils.isNotBlank(name)) {
                        completionParameter.getResult().addElement(LookupElementBuilder.create(underscore(name)));
                    }
                }
            }
        }
    }

}
 
Example #5
Source File: InvalidQuantityInspection.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder problemsHolder, boolean b) {
    if (!TYPO3CMSProjectSettings.isEnabled(problemsHolder.getProject())) {
        return new PhpElementVisitor() {
        };
    }

    return new PhpElementVisitor() {
        @Override
        public void visitPhpElement(PhpPsiElement element) {

            boolean isArrayStringValue = PhpElementsUtil.isStringArrayValue().accepts(element);
            if (!isArrayStringValue || !insideTCAColumnDefinition(element)) {
                return;
            }

            String arrayIndex = extractArrayIndexFromValue(element);
            if (arrayIndex != null && Arrays.asList(TCAUtil.TCA_NUMERIC_CONFIG_KEYS).contains(arrayIndex)) {
                if (element instanceof StringLiteralExpression) {
                    problemsHolder.registerProblem(element, "Config key only accepts integer values");
                }
            }
        }
    };
}
 
Example #6
Source File: DoctrineClassOrmAnnotationGenerateAction.java    From idea-php-annotation-plugin with MIT License 5 votes vote down vote up
protected void execute(@NotNull Editor editor, @NotNull PhpClass phpClass, @NotNull PsiFile psiFile) {
    // insert ORM alias
    PhpPsiElement scopeForUseOperator = PhpCodeInsightUtil.findScopeForUseOperator(phpClass.getFirstChild());
    if(scopeForUseOperator != null) {
        PhpElementsUtil.insertUseIfNecessary(scopeForUseOperator, DoctrineUtil.DOCTRINE_ORM_MAPPING, "ORM");
        PsiDocumentManager.getInstance(psiFile.getProject()).doPostponedOperationsAndUnblockDocument(editor.getDocument());
    }

    PhpDocUtil.addClassOrmDocs(phpClass, editor.getDocument(), psiFile);
}
 
Example #7
Source File: MissingRenderTypeInspection.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildRealVisitor(@NotNull ProblemsHolder problemsHolder, boolean b) {
    return new PhpElementVisitor() {
        @Override
        public void visitPhpElement(PhpPsiElement element) {

            boolean isArrayStringValue = PhpElementsUtil.isStringArrayValue().accepts(element);
            if (!isArrayStringValue || !insideTCAColumnDefinition(element)) {
                return;
            }


            String arrayIndex = extractArrayIndexFromValue(element);
            if (arrayIndex != null && arrayIndex.equals("renderType")) {
                if (element instanceof StringLiteralExpression) {
                    String tableName = ((StringLiteralExpression) element).getContents();
                    boolean isValidRenderType = TCAUtil.getAvailableRenderTypes(element).contains(tableName);

                    if (!isValidRenderType) {
                        problemsHolder.registerProblem(element, "Missing renderType definition");
                    }
                }
            }
        }
    };
}
 
Example #8
Source File: MissingTableInspection.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildRealVisitor(@NotNull ProblemsHolder problemsHolder, boolean b) {
    return new PhpElementVisitor() {
        @Override
        public void visitPhpElement(PhpPsiElement element) {

            boolean isArrayStringValue = PhpElementsUtil.isStringArrayValue().accepts(element);
            if (element == null || !isArrayStringValue || !insideTCAColumnDefinition(element)) {
                return;
            }

            String arrayKey = extractArrayIndexFromValue(element);
            if (arrayKey != null && arrayKey.equals("allowed") && element instanceof StringLiteralExpression && ((StringLiteralExpression) element).getContents().equals("*")) {
                return;
            }

            boolean valueIsTableNameFieldValue = arrayIndexIsTCATableNameField(element);
            if (valueIsTableNameFieldValue) {
                if (element instanceof StringLiteralExpression) {
                    String tableName = ((StringLiteralExpression) element).getContents();
                    boolean isValidTableName = TableUtil.getAvailableTableNames(element.getProject()).contains(tableName);

                    if (!isValidTableName) {
                        problemsHolder.registerProblem(element, "Missing table definition");
                    }
                }
            }
        }
    };
}
 
Example #9
Source File: ImportUseForAnnotationQuickFix.java    From idea-php-annotation-plugin with MIT License 5 votes vote down vote up
private void invoke(@NotNull PsiElement psiElement, @NotNull Pair<String, String> pair) {
    PhpPsiElement scopeForUseOperator = PhpCodeInsightUtil.findScopeForUseOperator(psiElement);
    if(scopeForUseOperator != null) {
        if (pair.getSecond() == null) {
            PhpAliasImporter.insertUseStatement(pair.getFirst(), scopeForUseOperator);
        } else {
            PhpAliasImporter.insertUseStatement(pair.getFirst(), pair.getSecond(), scopeForUseOperator);
        }
    }
}
 
Example #10
Source File: PhpDocTagAnnotation.java    From idea-php-annotation-plugin with MIT License 5 votes vote down vote up
/**
 * Get property psi element
 *
 * @param propertyName property name template=""
 * @return Property value
 */
@Nullable
public StringLiteralExpression getPropertyValuePsi(@NotNull String propertyName) {
    PhpPsiElement docAttrList = phpDocTag.getFirstPsiChild();
    if(docAttrList != null) {
        return PhpElementsUtil.getChildrenOnPatternMatch(docAttrList, AnnotationPattern.getPropertyIdentifierValue(propertyName));
    }

    return null;
}
 
Example #11
Source File: DoctrineOrmRepositoryIntention.java    From idea-php-annotation-plugin with MIT License 5 votes vote down vote up
private void insertAttribute(@NotNull Editor editor, @NotNull String repositoryClass, @NotNull PhpDocTag phpDocTag, @Nullable PhpPsiElement firstPsiChild) {
    if(firstPsiChild == null) return;

    String attr = "repositoryClass=\"" + repositoryClass + "\"";

    // we already have an attribute list
    if(firstPsiChild.getNode().getElementType() == PhpDocElementTypes.phpDocAttributeList) {

        // AttributeList: "()", "(aaa)"
        String text = StringUtils.trim(firstPsiChild.getText());
        text = StringUtils.strip(text, "(");
        text = StringUtils.strip(text, ")");

        if (text.contains(attr)) {
            return;
        }

        if(text.length() == 0) {
            // @ORM\Entity()
            editor.getDocument().insertString(firstPsiChild.getTextRange().getStartOffset() + 1, attr);
        } else {
            // @ORM\Entity(readOnly=true)
            editor.getDocument().insertString(firstPsiChild.getTextRange().getStartOffset() + 1, attr + ", ");
        }

        return;
    }

    // @ORM\Entity
    PsiElement firstChild = phpDocTag.getFirstChild();
    if(firstChild != null) {
        editor.getDocument().insertString(firstChild.getTextRange().getEndOffset(), "(" + attr + ")");
    }
}
 
Example #12
Source File: DoctrineOrmRepositoryIntention.java    From idea-php-annotation-plugin with MIT License 5 votes vote down vote up
/**
 * Scope resolve for PhpClass:
 * "@ORM\Entity" or inside PhpClass
 */
@Nullable
private PhpClass getScopedPhpClass(PsiElement element) {

    // inside "@ORM\Entity"
    PsiElement parent = element.getParent();

    // inside "@ORM\Entity(<caret>)"
    if(parent.getNode().getElementType() == PhpDocElementTypes.phpDocAttributeList) {
        parent = parent.getParent();
    }

    if(parent instanceof PhpDocTag) {
        PhpDocTagAnnotation phpDocAnnotationContainer = AnnotationUtil.getPhpDocAnnotationContainer((PhpDocTag) parent);

        if(phpDocAnnotationContainer != null) {
            PhpClass phpClass = phpDocAnnotationContainer.getPhpClass();
            if("Doctrine\\ORM\\Mapping\\Entity".equals(phpClass.getPresentableFQN())) {
                PsiElement docTag = parent.getParent();
                if(docTag instanceof PhpDocComment) {
                    PhpPsiElement nextPsiSibling = ((PhpDocComment) docTag).getNextPsiSibling();
                    if(nextPsiSibling instanceof PhpClass) {
                        return (PhpClass) nextPsiSibling;
                    }
                }
            }
        }

        return null;
    }

    // and finally check PhpClass class scope
    return PsiTreeUtil.getParentOfType(element, PhpClass.class);
}
 
Example #13
Source File: DoctrineEmbeddedClassAnnotationGenerateAction.java    From idea-php-annotation-plugin with MIT License 5 votes vote down vote up
protected void execute(@NotNull Editor editor, @NotNull PhpClass phpClass, @NotNull PsiFile psiFile) {
    // insert ORM alias
    PhpPsiElement scopeForUseOperator = PhpCodeInsightUtil.findScopeForUseOperator(phpClass.getFirstChild());
    if(scopeForUseOperator != null) {
        PhpElementsUtil.insertUseIfNecessary(scopeForUseOperator, DoctrineUtil.DOCTRINE_ORM_MAPPING, "ORM");
        PsiDocumentManager.getInstance(psiFile.getProject()).doPostponedOperationsAndUnblockDocument(editor.getDocument());
    }

    PhpDocUtil.addClassEmbeddedDocs(phpClass, editor.getDocument(), psiFile);
}
 
Example #14
Source File: MissingColumnTypeInspection.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildRealVisitor(@NotNull ProblemsHolder problemsHolder, boolean b) {
    return new PhpElementVisitor() {
        @Override
        public void visitPhpElement(PhpPsiElement element) {

            boolean isArrayStringValue = PhpElementsUtil.isStringArrayValue().accepts(element);
            if (!isArrayStringValue || !insideTCAColumnDefinition(element)) {
                return;
            }


            String arrayIndex = extractArrayIndexFromValue(element);
            if (arrayIndex != null && arrayIndex.equals("type")) {
                if (element instanceof StringLiteralExpression) {
                    String tableName = ((StringLiteralExpression) element).getContents();
                    boolean isValidRenderType = TCAUtil.getAvailableColumnTypes(element.getProject()).contains(tableName);

                    if (!isValidRenderType) {
                        problemsHolder.registerProblem(element, "Missing column type definition");
                    }
                }
            }
        }
    };
}
 
Example #15
Source File: AnnotationRouteElementWalkingVisitor.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Nullable
private String getClassRoutePattern(@NotNull PhpDocTag phpDocTag) {
    PhpClass phpClass = PsiTreeUtil.getParentOfType(phpDocTag, PhpClass.class);
    if(phpClass == null) {
        return null;
    }

    PhpDocComment docComment = phpClass.getDocComment();
    for (PhpDocTag docTag : PsiTreeUtil.getChildrenOfTypeAsList(docComment, PhpDocTag.class)) {
        String classNameReference = AnnotationBackportUtil.getClassNameReference(docTag, this.fileImports);
        if(classNameReference == null) {
            continue;
        }

        if(!RouteHelper.isRouteClassAnnotation(classNameReference)) {
            continue;
        }

        PsiElement docAttr = PsiElementUtils.getChildrenOfType(docTag, PlatformPatterns.psiElement(PhpDocElementTypes.phpDocAttributeList));
        if(!(docAttr instanceof PhpPsiElement)) {
            continue;
        }

        PhpPsiElement firstPsiChild = ((PhpPsiElement) docAttr).getFirstPsiChild();
        if(!(firstPsiChild instanceof StringLiteralExpression)) {
            continue;
        }

        String contents = ((StringLiteralExpression) firstPsiChild).getContents();
        if(StringUtils.isNotBlank(contents)) {
            return contents;
        }
    }

    return null;
}
 
Example #16
Source File: AnnotationRouteElementWalkingVisitor.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private void extractMethods(@NotNull PhpDocTag phpDocTag, @NotNull StubIndexedRoute route) {
    PsiElement phpDoc = phpDocTag.getParent();
    if(!(phpDoc instanceof PhpDocComment)) {
        return;
    }

    PsiElement methodTag = ContainerUtil.find(phpDoc.getChildren(), psiElement ->
        psiElement instanceof PhpDocTag &&
            "\\Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Method".equals(
                AnnotationBackportUtil.getClassNameReference((PhpDocTag) psiElement, fileImports)
            )
    );

    if(!(methodTag instanceof PhpDocTag)) {
        return;
    }

    PhpPsiElement attrList = ((PhpDocTag) methodTag).getFirstPsiChild();
    if(attrList == null || attrList.getNode().getElementType() != PhpDocElementTypes.phpDocAttributeList) {
        return;
    }

    String content = attrList.getText();

    // ({"POST", "GET"}), ("POST")
    Matcher matcher = Pattern.compile("\"([\\w]{3,7})\"", Pattern.DOTALL).matcher(content);

    Collection<String> methods = new HashSet<>();
    while (matcher.find()) {
        methods.add(matcher.group(1).toLowerCase());
    }

    if(methods.size() > 0) {
        route.setMethods(methods);
    }
}
 
Example #17
Source File: EventAnnotationStubIndex.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private String findClassInstance(@NotNull PhpDocComment phpDocComment, @NotNull PhpDocTag phpDocTag) {
    PsiElement phpDocAttributeList = PsiElementUtils.getChildrenOfType(phpDocTag, PlatformPatterns.psiElement(PhpDocElementTypes.phpDocAttributeList));
    if(phpDocAttributeList instanceof PhpPsiElement) {
        PsiElement childrenOfType = PsiElementUtils.getChildrenOfType(phpDocAttributeList, PlatformPatterns.psiElement(PhpDocElementTypes.phpDocString));
        if(childrenOfType instanceof StringLiteralExpression) {
            String contents = StringUtils.stripStart(((StringLiteralExpression) childrenOfType).getContents(), "\\");
            if(StringUtils.isNotBlank(contents) && contents.length() < 350) {
                return contents;
            }
        }
    }

    return EventDispatcherUtil.extractEventClassInstance(phpDocComment.getText());
}
 
Example #18
Source File: EventAnnotationStubIndex.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private void visitPhpDocTag(PhpDocTag element) {
    String name = StringUtils.stripStart(element.getName(), "@");
    if(!"Event".equalsIgnoreCase(name)) {
        return;
    }

    PhpDocComment phpDocComment = ObjectUtils.tryCast(element.getParent(), PhpDocComment.class);
    if(phpDocComment == null) {
        return;
    }

    PhpPsiElement nextPsiSibling = phpDocComment.getNextPsiSibling();
    if(nextPsiSibling == null || nextPsiSibling.getNode().getElementType() != PhpElementTypes.CLASS_CONSTANTS) {
        return;
    }

    ClassConstImpl childOfAnyType = PsiTreeUtil.findChildOfAnyType(nextPsiSibling, ClassConstImpl.class);
    if(childOfAnyType == null) {
        return;
    }

    PsiElement defaultValue = childOfAnyType.getDefaultValue();
    if(!(defaultValue instanceof StringLiteralExpression)) {
        return;
    }

    String contents = ((StringLiteralExpression) defaultValue).getContents();

    String fqn = StringUtils.stripStart(childOfAnyType.getFQN(), "\\");

    map.put(contents, new DispatcherEvent(
        fqn,
        findClassInstance(phpDocComment, element))
    );
}
 
Example #19
Source File: DoctrineUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * Extract class and repository from all php annotations
 * We support multiple use case like orm an so on
 */
@NotNull
public static Collection<Pair<String, String>> getClassRepositoryPair(@NotNull PsiElement phpFile) {
    final Collection<Pair<String, String>> pairs = new ArrayList<>();

    phpFile.acceptChildren(new AnnotationElementWalkingVisitor(phpDocTag -> {
        PhpDocComment phpDocComment = PsiTreeUtil.getParentOfType(phpDocTag, PhpDocComment.class);
        if (phpDocComment == null) {
            return false;
        }

        PhpPsiElement phpClass = phpDocComment.getNextPsiSibling();
        if (!(phpClass instanceof PhpClass)) {
            return false;
        }

        PhpClass phpClassScope = (PhpClass) phpClass;

        pairs.add(Pair.create(
            phpClassScope.getPresentableFQN(),
            getAnnotationRepositoryClass(phpDocTag, phpClassScope))
        );

        return false;
    }, MODEL_CLASS_ANNOTATION));

    return pairs;
}
 
Example #20
Source File: ConfigEntityTypeAnnotationIndex.java    From idea-php-drupal-symfony2-bridge with MIT License 5 votes vote down vote up
@Override
public void visitElement(PsiElement element) {
    if(!(element instanceof PhpDocTag)) {
        super.visitElement(element);
        return;
    }

    String annotationName = StringUtils.stripStart(((PhpDocTag) element).getName(), "@");
    if(!"ConfigEntityType".equals(annotationName)) {
        super.visitElement(element);
        return;
    }

    PsiElement phpDocComment = element.getParent();
    if(!(phpDocComment instanceof PhpDocComment)) {
        super.visitElement(element);
        return;
    }

    PhpPsiElement phpClass = ((PhpDocComment) phpDocComment).getNextPsiSibling();
    if(!(phpClass instanceof PhpClass)) {
        super.visitElement(element);
        return;
    }

    String tagValue = element.getText();
    Matcher matcher = Pattern.compile("id\\s*=\\s*\"([\\w\\.-]+)\"").matcher(tagValue);
    if (matcher.find()) {
        map.put(matcher.group(1), StringUtils.stripStart(((PhpClass) phpClass).getFQN(), "\\"));
    }

    super.visitElement(element);
}
 
Example #21
Source File: MethodArgumentDroppedIndex.java    From idea-php-typo3-plugin with MIT License 4 votes vote down vote up
@NotNull
@Override
public DataIndexer<String, Integer, FileContent> getIndexer() {
    return inputData -> {
        Set<PsiElement> elements = new HashSet<>();

        Collections.addAll(
                elements,
                PsiTreeUtil.collectElements(inputData.getPsiFile(), el -> PlatformPatterns
                        .psiElement(StringLiteralExpression.class)
                        .withParent(
                                PlatformPatterns.psiElement(PhpElementTypes.ARRAY_KEY)
                                        .withAncestor(
                                                4,
                                                PlatformPatterns.psiElement(PhpElementTypes.RETURN)
                                        )
                        )
                        .accepts(el)
                )
        );

        Map<String, Integer> methodMap = new HashMap<>();

        for (PsiElement gatheredElement : elements) {
            PsiElement parent = gatheredElement.getParent().getParent();
            if (parent instanceof ArrayHashElement) {
                ArrayHashElement arr = (ArrayHashElement) parent;
                PhpPsiElement value = arr.getValue();
                if (value instanceof ArrayCreationExpression) {
                    ArrayCreationExpression creationExpression = (ArrayCreationExpression) value;
                    creationExpression.getHashElements().forEach(x -> {
                        PhpPsiElement key = x.getKey();
                        if (key != null && key.getText().contains("maximumNumberOfArguments")) {
                            methodMap.put("\\" + ((StringLiteralExpression) gatheredElement).getContents(), Integer.parseInt(x.getValue().getText()));
                        }
                    });
                }
            }
        }

        return methodMap;
    };
}
 
Example #22
Source File: AnnotationRouteElementWalkingVisitor.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
private void visitPhpDocTag(@NotNull PhpDocTag phpDocTag) {

        // "@var" and user non related tags dont need an action
        if(AnnotationBackportUtil.NON_ANNOTATION_TAGS.contains(phpDocTag.getName())) {
            return;
        }

        // init file imports
        if(this.fileImports == null) {
            this.fileImports = AnnotationBackportUtil.getUseImportMap(phpDocTag);
        }

        if(this.fileImports.size() == 0) {
            return;
        }

        String annotationFqnName = AnnotationBackportUtil.getClassNameReference(phpDocTag, this.fileImports);
        if(annotationFqnName == null || !RouteHelper.isRouteClassAnnotation(annotationFqnName)) {
            return;
        }

        PsiElement phpDocAttributeList = PsiElementUtils.getChildrenOfType(phpDocTag, PlatformPatterns.psiElement(PhpDocElementTypes.phpDocAttributeList));
        if(!(phpDocAttributeList instanceof PhpPsiElement)) {
            return;
        }

        String routeName = AnnotationUtil.getPropertyValue(phpDocTag, "name");
        if(routeName == null) {
            routeName = AnnotationBackportUtil.getRouteByMethod(phpDocTag);
        }

        if(routeName != null && StringUtils.isNotBlank(routeName)) {
            // prepend route name on PhpClass scope
            String routeNamePrefix = getRouteNamePrefix(phpDocTag);
            if(routeNamePrefix != null) {
                routeName = routeNamePrefix + routeName;
            }

            StubIndexedRoute route = new StubIndexedRoute(routeName);

            String path = "";

            // extract class path @Route("/foo") => "/foo" for prefixing upcoming methods
            String classPath = getClassRoutePattern(phpDocTag);
            if(classPath != null) {
                path += classPath;
            }

            // extract method path @Route("/foo") => "/foo"
            PhpPsiElement firstPsiChild = ((PhpPsiElement) phpDocAttributeList).getFirstPsiChild();
            if(firstPsiChild instanceof StringLiteralExpression) {
                String contents = ((StringLiteralExpression) firstPsiChild).getContents();
                if(StringUtils.isNotBlank(contents)) {
                    path += contents;
                }
            }

            if (path.length() > 0) {
                route.setPath(path);
            }

            route.setController(getController(phpDocTag));

            // @Method(...)
            extractMethods(phpDocTag, route);

            map.put(routeName, route);
        }
    }
 
Example #23
Source File: DoctrineOrmRepositoryIntention.java    From idea-php-annotation-plugin with MIT License 4 votes vote down vote up
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {

    PhpClass phpClass = getScopedPhpClass(element);
    if(phpClass == null) {
        return;
    }

    String fileName = phpClass.getName() + "Repository.php";
    String namespace = DoctrineUtil.trimBlackSlashes(phpClass.getNamespaceName());
    PsiDirectory dir = phpClass.getContainingFile().getContainingDirectory();

    PsiDirectory repositoryDir = dir;
    if (dir.getParentDirectory() != null) {
        PsiDirectory checkDir = dir.getParentDirectory().findSubdirectory("Repository");

        if (dir.findFile(fileName) == null && checkDir != null) {
            repositoryDir = checkDir;
        }
    }

    String repoClass = phpClass.getPresentableFQN() + "Repository";
    PhpClass repoPhpClass = PhpElementsUtil.getClass(project, repoClass);

    if (repoPhpClass == null && dir != repositoryDir) {
        // Entity/../Repository/
        namespace = phpClass.getNamespaceName();
        namespace = namespace.substring(0, namespace.lastIndexOf("\\"));
        namespace = namespace.substring(0, namespace.lastIndexOf("\\"));
        namespace = namespace + "\\Repository";
        namespace = DoctrineUtil.trimBlackSlashes(namespace);

        repoClass = namespace + "\\" + phpClass.getName() + "Repository";
        repoClass = PhpLangUtil.toPresentableFQN(repoClass);

        repoPhpClass = PhpElementsUtil.getClass(project, repoClass);
    }

    if(repoPhpClass == null) {
        if(repositoryDir.findFile(fileName) == null) {
            final FileTemplate fileTemplate = FileTemplateManager.getInstance(project).getTemplate("Doctrine Entity Repository");
            final Properties defaultProperties = FileTemplateManager.getInstance(project).getDefaultProperties();

            Properties properties = new Properties(defaultProperties);

            properties.setProperty("NAMESPACE", namespace);
            properties.setProperty("NAME", phpClass.getName() + "Repository");

            properties.setProperty("ENTITY_NAMESPACE", DoctrineUtil.trimBlackSlashes(phpClass.getNamespaceName()));
            properties.setProperty("ENTITY_NAME", phpClass.getName());

            try {
                PsiElement newElement = FileTemplateUtil.createFromTemplate(fileTemplate, fileName, properties, repositoryDir);

                new OpenFileDescriptor(project, newElement.getContainingFile().getVirtualFile(), 0).navigate(true);
            } catch (Exception e) {
                return;
            }
        } else {
            if (!ApplicationManager.getApplication().isHeadlessEnvironment()) {
                HintManager.getInstance().showErrorHint(editor, "Repository already exists ");
            }
        }
    }

    PhpDocTagAnnotation ormEntityPhpDocBlock = DoctrineUtil.getOrmEntityPhpDocBlock(phpClass);
    if(ormEntityPhpDocBlock != null) {
        PhpDocTag phpDocTag = ormEntityPhpDocBlock.getPhpDocTag();
        PhpPsiElement firstPsiChild = phpDocTag.getFirstPsiChild();
        insertAttribute(editor, repoClass, phpDocTag, firstPsiChild);
    }

}
 
Example #24
Source File: AnnotationTagInsertHandler.java    From idea-php-annotation-plugin with MIT License 4 votes vote down vote up
/**
 * Insert class alias before PhpStorm tries to import a new use statement "\Foo\Bar as Car"
 */
private void preAliasInsertion(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
    Collection<UseAliasOption> importsAliases = AnnotationUtil.getActiveImportsAliasesFromSettings();
    if(importsAliases.size() == 0) {
        return;
    }

    Object object = lookupElement.getObject();
    if(!(object instanceof PhpClass)) {
        return;
    }

    final String fqn = StringUtils.stripStart(((PhpClass) object).getFQN(), "\\");

    UseAliasOption useAliasOption = ContainerUtil.find(importsAliases, useAliasOption1 ->
        useAliasOption1.getAlias() != null &&
        useAliasOption1.getClassName() != null &&
        fqn.startsWith(StringUtils.stripStart(useAliasOption1.getClassName(), "\\"))
    );

    if(useAliasOption == null || useAliasOption.getClassName() == null || useAliasOption.getAlias() == null) {
        return;
    }

    PsiElement elementAt = context.getFile().findElementAt(context.getEditor().getCaretModel().getOffset());
    if(elementAt == null) {
        return;
    }


    PhpPsiElement scopeForUseOperator = PhpCodeInsightUtil.findScopeForUseOperator(elementAt);
    if(scopeForUseOperator == null) {
        return;
    }

    String className = useAliasOption.getClassName();
    if(!className.startsWith("\\")) {
        className = "\\" + className;
    }

    PhpElementsUtil.insertUseIfNecessary(scopeForUseOperator, className, useAliasOption.getAlias());
    PsiDocumentManager.getInstance(context.getProject()).doPostponedOperationsAndUnblockDocument(context.getDocument());
}
 
Example #25
Source File: PhpAnnotationTypeCompletionProvider.java    From idea-php-annotation-plugin with MIT License 4 votes vote down vote up
@Override
public void getPropertyValueCompletions(AnnotationPropertyParameter annotationPropertyParameter, AnnotationCompletionProviderParameter completionParameter) {
    String propertyName = annotationPropertyParameter.getPropertyName();
    if(!annotationPropertyParameter.getType().equals(AnnotationPropertyParameter.Type.PROPERTY_VALUE) && propertyName == null) {
        return;
    }

    Set<String> values = new HashSet<>();
    AnnotationUtil.visitAttributes(annotationPropertyParameter.getPhpClass(), (attributeName, type, target) -> {
        if(!attributeName.equals(propertyName)) {
            return null;
        }

        if (AnnotationPropertyEnum.fromString(type) == AnnotationPropertyEnum.BOOLEAN) {
            values.addAll(Arrays.asList("false", "true"));
        }

        // @Enum({"AUTO", "SEQUENCE"})
        if (target instanceof Field) {
            PhpDocComment docComment = ((Field) target).getDocComment();
            if(docComment != null) {
                PhpDocTag[] phpDocTags = docComment.getTagElementsByName("@Enum");
                for(PhpDocTag phpDocTag: phpDocTags) {
                    PhpPsiElement phpDocAttrList = phpDocTag.getFirstPsiChild();
                    if(phpDocAttrList != null) {
                        String enumArrayString = phpDocAttrList.getText();
                        Pattern targetPattern = Pattern.compile("\"(\\w+)\"");

                        Matcher matcher = targetPattern.matcher(enumArrayString);
                        while (matcher.find()) {
                            values.add(matcher.group(1));
                        }
                    }
                }
            }
        }

        return null;
    });

    for(String s: values) {
        completionParameter.getResult().addElement(LookupElementBuilder.create(s));
    }
}
 
Example #26
Source File: DoctrineAnnotationReferencedColumnReferences.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
@Nullable
@Override
public PsiReference[] getPropertyReferences(AnnotationPropertyParameter annotationPropertyParameter, PhpAnnotationReferenceProviderParameter phpAnnotationReferenceProviderParameter) {

    PsiElement element = annotationPropertyParameter.getElement();
    if(!Symfony2ProjectComponent.isEnabled(annotationPropertyParameter.getProject()) ||
        !(element instanceof StringLiteralExpression) ||
        !PhpElementsUtil.isEqualClassName(annotationPropertyParameter.getPhpClass(), "\\Doctrine\\ORM\\Mapping\\JoinColumn")
        )
    {
        return new PsiReference[0];
    }

    // @Foo(targetEntity="Foo\Class")
    if(annotationPropertyParameter.getType() == AnnotationPropertyParameter.Type.PROPERTY_VALUE && "referencedColumnName".equals(annotationPropertyParameter.getPropertyName())) {

        PhpDocComment phpDocComment = PsiTreeUtil.getParentOfType(element, PhpDocComment.class);
        if(phpDocComment != null) {
            PhpDocCommentAnnotation phpDocCommentAnnotationContainer = AnnotationUtil.getPhpDocCommentAnnotationContainer(phpDocComment);

            if(phpDocCommentAnnotationContainer != null) {

                PhpDocTagAnnotation phpDocTagAnnotation = phpDocCommentAnnotationContainer.getFirstPhpDocBlock(
                    "\\Doctrine\\ORM\\Mapping\\ManyToOne",
                    "\\Doctrine\\ORM\\Mapping\\ManyToMany",
                    "\\Doctrine\\ORM\\Mapping\\OneToOne",
                    "\\Doctrine\\ORM\\Mapping\\OneToMany"
                );

                if(phpDocTagAnnotation != null) {

                    PhpPsiElement phpDocAttrList = phpDocTagAnnotation.getPhpDocTag().getFirstPsiChild();

                    // @TODO: remove nested on Annotation plugin update
                    if(phpDocAttrList != null) {
                        if(phpDocAttrList.getNode().getElementType() == PhpDocElementTypes.phpDocAttributeList) {
                            PhpPsiElement phpPsiElement = phpDocAttrList.getFirstPsiChild();
                            if(phpPsiElement instanceof StringLiteralExpression) {
                                PhpClass phpClass = de.espend.idea.php.annotation.util.PhpElementsUtil.getClassInsideAnnotation(((StringLiteralExpression) phpPsiElement));
                                if(phpClass != null) {
                                    Collection<DoctrineModelField> lists = EntityHelper.getModelFields(phpClass);
                                    if(lists.size() > 0) {
                                        return new PsiReference[] {
                                            new EntityReference((StringLiteralExpression) element, lists)
                                        };
                                    }
                                }
                            }
                        }
                    }


                }

            }

        }

    }

    return new PsiReference[0];
}
 
Example #27
Source File: ViewCompletionProvider.java    From yiistorm with MIT License 4 votes vote down vote up
public ArrayList<String> getRenderParams(com.intellij.codeInsight.completion.CompletionParameters c) {
    PsiElement pEl = c.getLookup().getPsiElement();

    ArrayList<String> names = new ArrayList<String>();
    String creatorClassName = PsiPhpHelper.getClassName(pEl);
    if (creatorClassName != null && !creatorClassName.isEmpty()) {
        names.add("@var " + creatorClassName + " $this");
    }
    if (pEl != null) {
        PsiElement pString = pEl.getParent();
        if (pString != null) {
            PsiElement nextSibling = pString.getNextSibling();

            while ((nextSibling != null && !nextSibling.getClass().getSimpleName().contains("ArrayCreationExpressionImpl"))) {
                nextSibling = nextSibling.getNextSibling();
            }
            if (nextSibling != null) {
                PsiElement[] list = nextSibling.getChildren();
                for (PsiElement el : list) {

                    PsiElement[] keyValueList = el.getChildren();
                    if (keyValueList.length == 2) {
                        String keyText = "";
                        String valueType;
                        for (PsiElement keyValueEl : keyValueList) {

                            valueType = "";
                            PhpPsiElement kv = (PhpPsiElement) keyValueEl;

                            if (kv.toString().equals("Array key")) {
                                keyText = keyValueEl.getText().replace("'", "");
                            }

                            if (kv.toString().equals("Array value")) {
                                for (PsiElement psiElement : kv.getChildren()) {
                                    valueType = PsiPhpTypeHelper.detectType(psiElement);
                                }
                                //Standartize some types
                                if (keyText != null && !valueType.equals("")) {

                                    names.add("@var " + valueType + " $" + keyText);
                                }
                                keyText = null;
                            }

                        }


                    }
                }

            }
        }
    }


    return names;
}
 
Example #28
Source File: InternalTypeFileInspection.java    From idea-php-typo3-plugin with MIT License 4 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder problemsHolder, boolean b) {
    if (!TYPO3CMSProjectSettings.getInstance(problemsHolder.getProject()).pluginEnabled) {
        return new PhpElementVisitor() {
        };
    }

    // the internal type was deprecated on 9 and dropped on 10
    if (TYPO3Utility.compareMajorMinorVersion(problemsHolder.getProject(), "9.0") < 0) {
        return new PhpElementVisitor() {
        };
    }

    return new PhpElementVisitor() {
        @Override
        public void visitPhpElement(PhpPsiElement element) {

            boolean isArrayStringValue = PhpElementsUtil.isStringArrayValue().accepts(element);
            if (!isArrayStringValue || !insideTCAColumnDefinition(element)) {
                return;
            }


            String arrayIndex = extractArrayIndexFromValue(element);
            if (arrayIndex != null && arrayIndex.equals("internal_type")) {
                if (element instanceof StringLiteralExpression) {
                    String internalType = ((StringLiteralExpression) element).getContents();

                    if (!internalType.equals("file_reference") && !internalType.equals("file")) {
                        return;
                    }

                    // the internal type was deprecated on 9 and dropped on 10
                    if (TYPO3Utility.compareMajorMinorVersion(problemsHolder.getProject(), "10.0") < 0) {
                        problemsHolder.registerProblem(element, String.format("Internal type '%s' is deprecated, will be removed with v10.0", internalType), ProblemHighlightType.LIKE_DEPRECATED);

                        return;
                    }

                    problemsHolder.registerProblem(element, String.format("Internal type '%s' was removed prior to v10.0", internalType), ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
                }
            }
        }
    };
}