Java Code Examples for fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil#getClassInterface()

The following examples show how to use fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil#getClassInterface() . 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: ExtJsTemplateLineMarkerProvider.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
private void attachController(Project project, String[] namespaces, List<PsiElement> targets) {

        if(namespaces.length < 4) {
            return;
        }

        // only show on some context
        if(!Arrays.asList("controller", "store", "model", "view").contains(namespaces[3])) {
            return;
        }

        String controller = namespaces[2];

        // build class name
        String className = String.format("\\Shopware_Controllers_%s_%s", "Backend", controller);
        PhpClass phpClass = PhpElementsUtil.getClassInterface(project, className);
        if(phpClass != null) {
            targets.add(phpClass);
        }

    }
 
Example 2
Source File: ServiceUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
public static Set<String> getServiceSuggestionsForServiceConstructorIndex(@NotNull Project project, @NotNull String serviceName, int index) {
    PhpClass phpClass = ServiceUtil.getResolvedClassDefinition(project, serviceName);
    // check type hint on constructor
    if(phpClass == null) {
        return Collections.emptySet();
    }

    Method constructor = phpClass.getConstructor();
    if(constructor == null) {
        return Collections.emptySet();
    }

    Parameter[] constructorParameter = constructor.getParameters();
    if(index >= constructorParameter.length) {
        return Collections.emptySet();
    }

    String className = constructorParameter[index].getDeclaredType().toString();
    PhpClass expectedClass = PhpElementsUtil.getClassInterface(project, className);
    if(expectedClass == null) {
        return Collections.emptySet();
    }

    return ServiceActionUtil.getPossibleServices(expectedClass, ContainerCollectionResolver.getServices(project));
}
 
Example 3
Source File: ServiceUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
public static Collection<ContainerService> getServiceSuggestionForPhpClass(@NotNull PhpClass phpClass, @NotNull Collection<ContainerService> serviceMap) {

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

    Collection<ContainerService> instances = new ArrayList<>();

    for(ContainerService service: serviceMap) {
        if(service.getClassName() == null) {
            continue;
        }

        PhpClass serviceClass = PhpElementsUtil.getClassInterface(phpClass.getProject(), service.getClassName());
        if(serviceClass == null) {
            continue;
        }

        if(PhpElementsUtil.isInstanceOf(serviceClass, fqn)) {
            instances.add(service);
        }
    }

    return instances;
}
 
Example 4
Source File: ServiceUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * Resolve "@service" to its class
 */
@Nullable
public static PhpClass getServiceClass(@NotNull Project project, @NotNull String serviceName) {

    serviceName = YamlHelper.trimSpecialSyntaxServiceName(serviceName);

    if(serviceName.length() == 0) {
        return null;
    }

    ContainerService containerService = ContainerCollectionResolver.getService(project, serviceName);
    if(containerService == null) {
        return null;
    }

    String serviceClass = containerService.getClassName();
    if(serviceClass == null) {
        return null;
    }

    return PhpElementsUtil.getClassInterface(project, serviceClass);
}
 
Example 5
Source File: ConstantEnumCompletionContributor.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private void attachLookup(CompletionResultSet completionResultSet, MethodReference psiElement, ConstantEnumCompletionProvider enumProvider) {

        // we allow string values
        if(enumProvider.getEnumConstantFilter().getInstance() == null || enumProvider.getEnumConstantFilter().getField() == null) {
            return;
        }

        if(!PhpElementsUtil.isMethodReferenceInstanceOf(psiElement, enumProvider.getCallToSignature())) {
            return;
        }

        PhpClass phpClass = PhpElementsUtil.getClassInterface(psiElement.getProject(), enumProvider.getEnumConstantFilter().getInstance());
        if(phpClass == null) {
            return;
        }

        for(Field field: phpClass.getFields()) {
            if(field.isConstant() && field.getName().startsWith(enumProvider.getEnumConstantFilter().getField())) {
                completionResultSet.addElement(new PhpConstantFieldPhpLookupElement(field));
            }
        }

    }
 
Example 6
Source File: ServiceArgumentParameterHintsProvider.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
private String createTypeHintFromParameter(@NotNull Project project, Parameter parameter) {
    String className = parameter.getDeclaredType().toString();
    if(PhpType.isNotExtendablePrimitiveType(className)) {
        return parameter.getName();
    }

    int i = className.lastIndexOf("\\");
    if(i > 0) {
        return className.substring(i + 1);
    }

    PhpClass expectedClass = PhpElementsUtil.getClassInterface(project, className);
    if(expectedClass != null) {
        return expectedClass.getName();
    }

    return parameter.getName();
}
 
Example 7
Source File: YamlClassInspection.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private void invoke(@NotNull final PsiElement psiElement, @NotNull ProblemsHolder holder) {
    String className = PsiElementUtils.getText(psiElement);

    if (YamlHelper.isValidParameterName(className)) {
        String resolvedParameter = ContainerCollectionResolver.resolveParameter(psiElement.getProject(), className);
        if (resolvedParameter != null && PhpIndex.getInstance(psiElement.getProject()).getAnyByFQN(resolvedParameter).size() > 0) {
            return;
        }
    }

    PhpClass foundClass = PhpElementsUtil.getClassInterface(psiElement.getProject(), className);
    if (foundClass == null) {
        holder.registerProblem(psiElement, MESSAGE_MISSING_CLASS, ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
    } else if (!foundClass.getPresentableFQN().equals(className)) {
        holder.registerProblem(psiElement, MESSAGE_WRONG_CASING, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, new CorrectClassNameCasingYamlLocalQuickFix(foundClass.getPresentableFQN()));
    }
}
 
Example 8
Source File: QueryBuilderMethodReferenceParser.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private void buildPropertyMap(QueryBuilderScopeContext qb) {

        if(!collectProperties) {
            return;
        }

        for(QueryBuilderJoin join: qb.getJoinMap().values()) {
            String className = join.getResolvedClass();
            if(className != null) {
                PhpClass phpClass = PhpElementsUtil.getClassInterface(project, className);
                if(phpClass != null) {
                    qb.addPropertyAlias(join.getAlias(), new QueryBuilderPropertyAlias(join.getAlias(), null, new DoctrineModelField(join.getAlias()).addTarget(phpClass).setTypeName(phpClass.getPresentableFQN())));

                    // add entity properties
                    for(DoctrineModelField field: EntityHelper.getModelFields(phpClass)) {
                        qb.addPropertyAlias(join.getAlias() + "." + field.getName(), new QueryBuilderPropertyAlias(join.getAlias(), field.getName(), field));
                    }
                }
            }
        }

    }
 
Example 9
Source File: DoctrineMetadataUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@NotNull
public static Collection<PhpClass> getModels(@NotNull Project project) {

    Collection<PhpClass> phpClasses = new ArrayList<>();
    for (String key : FileIndexCaches.getIndexKeysCache(project, CLASS_KEYS, DoctrineMetadataFileStubIndex.KEY)) {
        PhpClass classInterface = PhpElementsUtil.getClassInterface(project, key);
        if(classInterface != null) {
            phpClasses.add(classInterface);
        }
    }

    return phpClasses;
}
 
Example 10
Source File: QueryBuilderRelationClassResolver.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
public void collect() {

        for(QueryBuilderJoin queryBuilderJoin: joinMap.values()) {
            if(queryBuilderJoin.getResolvedClass() == null) {
                String joinName = queryBuilderJoin.getJoin();
                String[] split = StringUtils.split(joinName, ".");
                if(split.length == 2) {

                    // alias.foreignProperty
                    String foreignJoinAlias = split[0];
                    String foreignJoinField = split[1];

                    if(relationMap.containsKey(foreignJoinAlias)) {
                        for(QueryBuilderRelation queryBuilderRelation: relationMap.get(foreignJoinAlias)) {
                            if(queryBuilderRelation.getFieldName().equals(foreignJoinField)) {
                                String targetEntity = queryBuilderRelation.getTargetEntity();
                                if(targetEntity != null) {
                                    PhpClass phpClass = PhpElementsUtil.getClassInterface(project, targetEntity);
                                    if(phpClass != null) {
                                        relationMap.put(queryBuilderJoin.getAlias(), QueryBuilderMethodReferenceParser.attachRelationFields(phpClass));
                                        queryBuilderJoin.setResolvedClass(targetEntity);
                                        collect();
                                    }
                                }

                            }
                        }

                    }

                }

            }
        }

    }
 
Example 11
Source File: ServiceActionUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@NotNull
public static Set<String> getPossibleServices(@NotNull Project project, @NotNull String type, @NotNull Map<String, ContainerService> serviceClasses) {
    PhpClass typeClass = PhpElementsUtil.getClassInterface(project, type);
    if(typeClass == null) {
        return Collections.emptySet();
    }

    return getPossibleServices(typeClass, serviceClasses);
}
 
Example 12
Source File: YamlXmlServiceInstanceInspection.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
static void registerInstanceProblem(@NotNull PsiElement psiElement, @NotNull ProblemsHolder holder, int parameterIndex, @NotNull Method constructor, @NotNull ContainerCollectionResolver.LazyServiceCollector lazyServiceCollector) {
    String serviceName = getServiceName(psiElement);
    if(StringUtils.isBlank(serviceName)) {
        return;
    }

    PhpClass serviceParameterClass = ServiceUtil.getResolvedClassDefinition(psiElement.getProject(), getServiceName(psiElement), lazyServiceCollector);
    if(serviceParameterClass == null) {
        return;
    }

    Parameter[] constructorParameter = constructor.getParameters();
    if(parameterIndex >= constructorParameter.length) {
        return;
    }

    PhpClass expectedClass = PhpElementsUtil.getClassInterface(psiElement.getProject(), constructorParameter[parameterIndex].getDeclaredType().toString());
    if(expectedClass == null) {
        return;
    }

    if(!PhpElementsUtil.isInstanceOf(serviceParameterClass, expectedClass)) {
        holder.registerProblem(
            psiElement,
            "Expect instance of: " + expectedClass.getPresentableFQN(),
            new YamlSuggestIntentionAction(expectedClass.getFQN(), psiElement)
        );
    }
}
 
Example 13
Source File: QueryBuilderGotoDeclarationHandler.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private void attachJoinGoto(StringLiteralExpression psiElement, List<PsiElement> targets) {

        MethodMatcher.MethodMatchParameter methodMatchParameter = MatcherUtil.matchJoin(psiElement);
        if(methodMatchParameter == null) {
            return;
        }

        QueryBuilderMethodReferenceParser qb = QueryBuilderCompletionContributor.getQueryBuilderParser(methodMatchParameter.getMethodReference());
        if(qb == null) {
            return;
        }

        String[] joinSplit = StringUtils.split(psiElement.getContents(), ".");
        if(joinSplit.length != 2) {
            return;
        }

        QueryBuilderScopeContext collect = qb.collect();
        if(!collect.getRelationMap().containsKey(joinSplit[0])) {
            return;
        }

        List<QueryBuilderRelation> relations = collect.getRelationMap().get(joinSplit[0]);
        for(QueryBuilderRelation relation: relations) {
            if(joinSplit[1].equals(relation.getFieldName()) && relation.getTargetEntity() != null) {
                PhpClass phpClass = PhpElementsUtil.getClassInterface(psiElement.getProject(), relation.getTargetEntity());
                if(phpClass != null) {
                    targets.add(phpClass);
                }

            }
        }


    }
 
Example 14
Source File: TwigTemplateGoToDeclarationHandler.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@NotNull
private Collection<PsiElement> getConstantGoto(@NotNull PsiElement psiElement) {
    Collection<PsiElement> targetPsiElements = new ArrayList<>();

    String contents = psiElement.getText();
    if(StringUtils.isBlank(contents)) {
        return targetPsiElements;
    }

    // global constant
    if(!contents.contains(":")) {
        targetPsiElements.addAll(PhpIndex.getInstance(psiElement.getProject()).getConstantsByName(contents));
        return targetPsiElements;
    }

    // resolve class constants
    String[] parts = contents.split("::");
    if(parts.length != 2) {
        return targetPsiElements;
    }

    PhpClass phpClass = PhpElementsUtil.getClassInterface(psiElement.getProject(), parts[0].replace("\\\\", "\\"));
    if(phpClass == null) {
        return targetPsiElements;
    }

    Field field = phpClass.findFieldByName(parts[1], true);
    if(field != null) {
        targetPsiElements.add(field);
    }

    return targetPsiElements;
}
 
Example 15
Source File: TwigTypeResolveUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * Extract magic iterator implementation like "getIterator" or "__iterator"
 *
 * "@TODO find core stuff for resolve possible class return values"
 *
 * "getIterator", "@method Foo __iterator", "@method Foo[] __iterator"
 */
@NotNull
private static Set<String> collectIteratorReturns(@NotNull PsiElement psiElement, @NotNull Set<String> types) {
    Set<String> arrayValues = new HashSet<>();
    for (String type : types) {
        PhpClass phpClass = PhpElementsUtil.getClassInterface(psiElement.getProject(), type);

        if(phpClass == null) {
            continue;
        }

        for (String methodName : new String[]{"getIterator", "__iterator", "current"}) {
            Method method = phpClass.findMethodByName(methodName);
            if(method != null) {
                // @method Foo __iterator
                // @method Foo[] __iterator
                Set<String> iteratorTypes = method.getType().getTypes();
                if("__iterator".equals(methodName) || "current".equals(methodName)) {
                    arrayValues.addAll(iteratorTypes.stream().map(x ->
                        !x.endsWith("[]") ? x + "[]" : x
                    ).collect(Collectors.toSet()));
                } else {
                    // Foobar[]
                    for (String iteratorType : iteratorTypes) {
                        if(iteratorType.endsWith("[]")) {
                            arrayValues.add(iteratorType);
                        }
                    }
                }
            }
        }
    }

    return arrayValues;
}
 
Example 16
Source File: TwigTypeResolveUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private static Collection<TwigTypeContainer> resolveTwigMethodName(Collection<TwigTypeContainer> previousElement, String typeName, Collection<List<TwigTypeContainer>> twigTypeContainer) {

        ArrayList<TwigTypeContainer> phpNamedElements = new ArrayList<>();

        for(TwigTypeContainer phpNamedElement: previousElement) {

            if(phpNamedElement.getPhpNamedElement() != null) {
                for(PhpNamedElement target : getTwigPhpNameTargets(phpNamedElement.getPhpNamedElement(), typeName)) {
                    PhpType phpType = target.getType();

                    // @TODO: provide extension
                    // custom resolving for Twig here: "app.user" => can also be a general solution just support the "getToken()->getUser()"
                    if (target instanceof Method && StaticVariableCollector.isUserMethod((Method) target)) {
                        phpNamedElements.addAll(getApplicationUserImplementations(target.getProject()));
                    }

                    // @TODO: use full resolving for object, that would allow using TypeProviders and core PhpStorm feature
                    for (String typeString: phpType.filterPrimitives().getTypes()) {
                        PhpClass phpClass = PhpElementsUtil.getClassInterface(phpNamedElement.getPhpNamedElement().getProject(), typeString);
                        if(phpClass != null) {
                            phpNamedElements.add(new TwigTypeContainer(phpClass));
                        }
                    }
                }
            }

            for(TwigTypeResolver twigTypeResolver: TWIG_TYPE_RESOLVERS) {
                twigTypeResolver.resolve(phpNamedElements, previousElement, typeName, twigTypeContainer, null);
            }

        }

        return phpNamedElements;
    }
 
Example 17
Source File: ShopwareUtil.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
@Nullable
public static Method getControllerActionOnSmartyFile(SmartyFile smartyFile, String... modules) {

    String relativeFilename = TemplateUtil.getTemplateName(smartyFile.getProject(), smartyFile.getVirtualFile());
    if(relativeFilename == null) {
        return null;
    }

    Pattern pattern = Pattern.compile(".*[/]*(" + StringUtils.join(modules, "|") + ")/(\\w+)/(\\w+)\\.tpl");
    Matcher matcher = pattern.matcher(relativeFilename);

    if(!matcher.find()) {
        return null;
    }

    // Shopware_Controllers_Frontend_Account
    String moduleName = toCamelCase(matcher.group(1), false);
    String controller = toCamelCase(matcher.group(2), false);
    String action = toCamelCase(matcher.group(3), true);

    // build class name
    String className = String.format("\\Shopware_Controllers_%s_%s", moduleName, controller);
    PhpClass phpClass = PhpElementsUtil.getClassInterface(smartyFile.getProject(), className);
    if(phpClass == null) {
        return null;
    }

    return phpClass.findMethodByName(action + "Action");

}
 
Example 18
Source File: SmartyTemplateLineMarkerProvider.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
public void attachController(SmartyFile smartyFile, final List<GotoRelatedItem> gotoRelatedItems) {

        String relativeFilename = TemplateUtil.getTemplateName(smartyFile.getProject(), smartyFile.getVirtualFile());
        if(relativeFilename == null) {
            return;
        }

        Pattern pattern = Pattern.compile(".*[/]*(frontend|backend|core)/(\\w+)/(\\w+)\\.tpl");
        Matcher matcher = pattern.matcher(relativeFilename);

        if(!matcher.find()) {
            return;
        }

        // Shopware_Controllers_Frontend_Account
        String moduleName = ShopwareUtil.toCamelCase(matcher.group(1), false);
        String controller = ShopwareUtil.toCamelCase(matcher.group(2), false);
        String action = ShopwareUtil.toCamelCase(matcher.group(3), true);

        // build class name
        String className = String.format("\\Shopware_Controllers_%s_%s", moduleName, controller);
        PhpClass phpClass = PhpElementsUtil.getClassInterface(smartyFile.getProject(), className);
        if(phpClass == null) {
            return;
        }

        Method method = phpClass.findMethodByName(action + "Action");
        if(method != null) {
            gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(method, "Navigate to action").withIcon(PhpIcons.METHOD, PhpIcons.METHOD));
            return;
        }

        // fallback to class
        gotoRelatedItems.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(phpClass, "Navigate to class").withIcon(PhpIcons.CLASS, PhpIcons.CLASS));

    }
 
Example 19
Source File: ShopwareProjectComponent.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
public static boolean isValidForProject(@Nullable Project project) {
    if(project == null || Symfony2ProjectComponent.isEnabled(project)) {
        return true;
    }

    if(VfsUtil.findRelativeFile(project.getBaseDir(), "engine", "Shopware", "Kernel.php") != null) {
        return true;
    }

    return PhpElementsUtil.getClassInterface(project, "\\Enlight_Controller_Action") != null;
}
 
Example 20
Source File: ServiceArgumentSelectionDialog.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
@Nullable
@Override
public Icon valueOf(ServiceParameter modelParameter) {
    PhpClass classInterface = PhpElementsUtil.getClassInterface(project, modelParameter.getClassFqn());
    return classInterface != null ? classInterface.getIcon() : null;
}