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

The following examples show how to use fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil#isInstanceOf() . 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: XmlServiceInstanceInspection.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private void attachMethodInstances(@NotNull PsiElement target, @NotNull String serviceName, @NotNull Method method, int parameterIndex, @NotNull ProblemsHolder holder) {
    Parameter[] constructorParameter = method.getParameters();
    if(parameterIndex >= constructorParameter.length) {
        return;
    }

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

    PhpClass serviceParameterClass = ServiceUtil.getResolvedClassDefinition(method.getProject(), serviceName);
    if(serviceParameterClass != null && !PhpElementsUtil.isInstanceOf(serviceParameterClass, expectedClass)) {
        holder.registerProblem(
            target,
            "Expect instance of: " + expectedClass.getPresentableFQN(),
            ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
            new XmlServiceSuggestIntentionAction(expectedClass.getFQN(), target)
        );
    }
}
 
Example 2
Source File: ServiceUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 *  Gets all tags on extends/implements path of class
 */
@NotNull
public static Set<String> getPhpClassServiceTags(@NotNull PhpClass phpClass) {

    Set<String> tags = new HashSet<>();

    for (Map.Entry<String, String> entry : TAG_INTERFACES.entrySet()) {

        if(entry.getValue() == null) {
            continue;
        }

        if(PhpElementsUtil.isInstanceOf(phpClass, entry.getValue())) {
            tags.add(entry.getKey());
        }

    }

    // strong tags wins
    if(tags.size() > 0) {
        return tags;
    }

    // try to resolve on indexed tags
    return getPhpClassTags(phpClass);
}
 
Example 3
Source File: ServiceLineMarkerProvider.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * "FooValidator" back to "Foo" constraint
 */
private void constraintValidatorClassMarker(PsiElement psiElement, Collection<LineMarkerInfo> results) {
    PsiElement phpClass = psiElement.getContext();
    if(!(phpClass instanceof PhpClass) || !PhpElementsUtil.isInstanceOf((PhpClass) phpClass, "Symfony\\Component\\Validator\\ConstraintValidatorInterface")) {
        return;
    }

    String fqn = ((PhpClass) phpClass).getFQN();
    if(!fqn.endsWith("Validator")) {
        return;
    }

    Collection<PhpClass> phpClasses = new ArrayList<>(
        PhpElementsUtil.getClassesInterface(psiElement.getProject(), fqn.substring(0, fqn.length() - "Validator".length()))
    );

    if(phpClasses.size() == 0) {
        return;
    }

    NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(Symfony2Icons.SYMFONY_LINE_MARKER).
        setTargets(phpClasses).
        setTooltipText("Navigate to constraint");

    results.add(builder.createLineMarkerInfo(psiElement));
}
 
Example 4
Source File: ServiceLineMarkerProvider.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * Constraints in same namespace and validateBy service name
 */
private void validatorClassMarker(PsiElement psiElement, Collection<LineMarkerInfo> results) {
    PsiElement phpClassContext = psiElement.getContext();
    if(!(phpClassContext instanceof PhpClass) || !PhpElementsUtil.isInstanceOf((PhpClass) phpClassContext, "\\Symfony\\Component\\Validator\\Constraint")) {
        return;
    }

    // class in same namespace
    String className = ((PhpClass) phpClassContext).getFQN() + "Validator";
    Collection<PhpClass> phpClasses = new ArrayList<>(PhpElementsUtil.getClassesInterface(psiElement.getProject(), className));

    // @TODO: validateBy alias

    if(phpClasses.size() == 0) {
        return;
    }

    NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(Symfony2Icons.SYMFONY_LINE_MARKER).
        setTargets(phpClasses).
        setTooltipText("Navigate to validator");

    results.add(builder.createLineMarkerInfo(psiElement));
}
 
Example 5
Source File: FormVarsResolver.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
public void resolve(Collection<TwigTypeContainer> targets, Collection<TwigTypeContainer> previousElement, String typeName, Collection<List<TwigTypeContainer>> previousElements, @Nullable Collection<PsiVariable> psiVariables) {
    if(!"vars".equals(typeName) || previousElements.size() == 0) {
        return;
    }

    List<TwigTypeContainer> lastTwigTypeContainer = null;
    for (Iterator collectionItr = previousElements.iterator(); collectionItr.hasNext(); ) {
        lastTwigTypeContainer = (List<TwigTypeContainer>) collectionItr.next();
    }

    for(TwigTypeContainer twigTypeContainer: lastTwigTypeContainer) {
        if(twigTypeContainer.getPhpNamedElement() instanceof PhpClass) {
            if(PhpElementsUtil.isInstanceOf((PhpClass) twigTypeContainer.getPhpNamedElement(), "\\Symfony\\Component\\Form\\FormView")) {
                attachVars(twigTypeContainer.getPhpNamedElement().getProject(), targets);
            }
        }

    }

}
 
Example 6
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 7
Source File: ShopwareSubscriperMethodInspection.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
@Override
public void visitElement(PsiElement element) {
    if(element instanceof StringLiteralExpression) {
        String subscriperName = getHashKey((StringLiteralExpression) element);
        if(subscriperName != null) {
            Method method = PsiTreeUtil.getParentOfType(element, Method.class);
            if(method != null) {
                if("getSubscribedEvents".equals(method.getName())) {
                    PhpClass phpClass = method.getContainingClass();
                    if(phpClass != null && PhpElementsUtil.isInstanceOf(phpClass, "\\Enlight\\Event\\SubscriberInterface")) {
                        visitSubscriber(phpClass, (StringLiteralExpression) element, subscriperName);
                    }
                }
            }

        }
    }

    super.visitElement(element);
}
 
Example 8
Source File: PhpBundleFileFactory.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Nullable
public static PhpClass getPhpClassForCreateCompilerScope(@Nullable PhpClass phpClass) {

    if(phpClass == null) {
        return null;
    }

    if(!PhpElementsUtil.isInstanceOf(phpClass, "\\Symfony\\Component\\HttpKernel\\Bundle\\BundleInterface")) {
        return null;
    }

    return phpClass;
}
 
Example 9
Source File: FormUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@NotNull
public static Collection<String> getFormAliases(@NotNull PhpClass phpClass) {
    // check class implements form interface
    if(!PhpElementsUtil.isInstanceOf(phpClass, ABSTRACT_FORM_INTERFACE)) {
        return Collections.emptySet();
    }

    String className = FormUtil.getFormNameOfPhpClass(phpClass);
    if(className == null) {
        return Collections.emptySet();
    }

    return Collections.singleton(className);
}
 
Example 10
Source File: FormUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * Find form php class scope: FormType or FormExtension
 */
@Nullable
public static String getFormTypeClassFromScope(@NotNull PsiElement psiElement) {
    Method methodScope = PsiTreeUtil.getParentOfType(psiElement, Method.class);

    if(methodScope != null) {
        PhpClass phpClass = methodScope.getContainingClass();
        if(phpClass != null && (PhpElementsUtil.isInstanceOf(phpClass, "\\Symfony\\Component\\Form\\FormTypeInterface") || PhpElementsUtil.isInstanceOf(phpClass, "\\Symfony\\Component\\Form\\FormExtensionInterface"))) {
            return phpClass.getFQN();
        }
    }

    return null;
}
 
Example 11
Source File: FormTypeConstantMigrationAction.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Override
protected boolean isValidForFile(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
    if(!(file instanceof PhpFile) || !Symfony2ProjectComponent.isEnabled(project)) {
        return false;
    }

    PhpClass classAtCaret = PhpCodeEditUtil.findClassAtCaret(editor, file);

    return
        classAtCaret != null &&
        PhpElementsUtil.isInstanceOf(classAtCaret, "Symfony\\Component\\Form\\FormTypeInterface")
    ;
}
 
Example 12
Source File: PhpLineMarkerProvider.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
private void collectSubscriberTargets(@NotNull List<PsiElement> psiElements, final @NotNull Collection<LineMarkerInfo> lineMarkerInfos) {
    Collection<PhpClass> phpClasses = new ArrayList<>();

    for (PsiElement psiElement : psiElements) {
        if(psiElement instanceof PhpClass && PhpElementsUtil.isInstanceOf((PhpClass) psiElement, "Enlight\\Event\\SubscriberInterface")) {
            phpClasses.add((PhpClass) psiElement);
        }
    }

    for (PhpClass phpClass : phpClasses) {
        Method getSubscribedEvents = phpClass.findOwnMethodByName("getSubscribedEvents");
        if(getSubscribedEvents == null) {
            continue;
        }

        Map<String, Pair<String, PsiElement>> methodEvent = new HashMap<>();

        HookSubscriberUtil.visitSubscriberEvents(getSubscribedEvents, (event, methodName, key) ->
            methodEvent.put(methodName, Pair.create(event, key))
        );

        for (Method method : phpClass.getOwnMethods()) {
            if(!methodEvent.containsKey(method.getName()) || !method.getAccess().isPublic()) {
                continue;
            }

            Pair<String, PsiElement> result = methodEvent.get(method.getName());
            NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(ShopwarePluginIcons.SHOPWARE_LINEMARKER).
                setTargets(new MyCollectionNotNullLazyValue(result.getSecond(), result.getFirst())).
                setTooltipText("Related Targets");

            // attach linemarker to leaf item which is our function name for performance reasons
            ASTNode node = method.getNode().findChildByType(PhpTokenTypes.IDENTIFIER);
            if(node != null) {
                lineMarkerInfos.add(builder.createLineMarkerInfo(node.getPsi()));
            }
        }
    }
}
 
Example 13
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 14
Source File: EventMethodCallInspection.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Override
public void visitElement(PsiElement element) {
    super.visitElement(element);

    if(!(element instanceof StringLiteralExpression)) {
        return;
    }

    PsiElement arrayValue = element.getParent();
    if(arrayValue != null && arrayValue.getNode().getElementType() == PhpElementTypes.ARRAY_VALUE) {
        PhpReturn phpReturn = PsiTreeUtil.getParentOfType(arrayValue, PhpReturn.class);
        if(phpReturn != null) {
            Method method = PsiTreeUtil.getParentOfType(arrayValue, Method.class);
            if(method != null) {
                String name = method.getName();
                if("getSubscribedEvents".equals(name)) {
                    PhpClass containingClass = method.getContainingClass();
                    if(containingClass != null && PhpElementsUtil.isInstanceOf(containingClass, "\\Symfony\\Component\\EventDispatcher\\EventSubscriberInterface")) {
                        String contents = ((StringLiteralExpression) element).getContents();
                        if(StringUtils.isNotBlank(contents) && containingClass.findMethodByName(contents) == null) {
                            registerMethodProblem(element, holder, containingClass);
                        }
                    }
                }
            }
        }
    }
}
 
Example 15
Source File: ThemeUtil.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
public static void collectThemeJsFieldReferences(@NotNull StringLiteralExpression element, @NotNull ThemeAssetVisitor visitor) {

        PsiElement arrayValue = element.getParent();
        if(arrayValue.getNode().getElementType() != PhpElementTypes.ARRAY_VALUE) {
            return;
        }

        PsiElement arrayCreation = arrayValue.getParent();
        if(!(arrayCreation instanceof ArrayCreationExpression)) {
            return;
        }

        PsiElement classField = arrayCreation.getParent();
        if(!(classField instanceof Field)) {
            return;
        }

        if(!"javascript".equals(((Field) classField).getName())) {
            return;
        }


        PhpClass phpClass = PsiTreeUtil.getParentOfType(classField, PhpClass.class);
        if(phpClass == null || !PhpElementsUtil.isInstanceOf(phpClass, "\\Shopware\\Components\\Theme")) {
            return;
        }

        visitThemeAssetsFile(phpClass, visitor);
    }
 
Example 16
Source File: TranslationPsiParser.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
public void parse(File file) {
    VirtualFile virtualFile = VfsUtil.findFileByIoFile(file, true);
    if(virtualFile == null) {
        Symfony2ProjectComponent.getLogger().info("VfsUtil missing translation: " + file.getPath());
        return;
    }

    PsiFile psiFile;
    try {
        psiFile = PhpPsiElementFactory.createPsiFileFromText(this.project, StreamUtil.readText(virtualFile.getInputStream(), "UTF-8"));
    } catch (IOException e) {
        return;
    }

    if(psiFile == null) {
        return;
    }

    Symfony2ProjectComponent.getLogger().info("update translations: " + file.getPath());

    Collection<NewExpression> messageCatalogues = PsiTreeUtil.collectElementsOfType(psiFile, NewExpression.class);
    for(NewExpression newExpression: messageCatalogues) {
        ClassReference classReference = newExpression.getClassReference();
        if(classReference != null) {
            PsiElement constructorMethod = classReference.resolve();
            if(constructorMethod instanceof Method) {
                PhpClass phpClass = ((Method) constructorMethod).getContainingClass();
                if(phpClass != null && PhpElementsUtil.isInstanceOf(phpClass, "\\Symfony\\Component\\Translation\\MessageCatalogueInterface")) {
                    this.getTranslationMessages(newExpression);
                }
            }
        }
    }
}
 
Example 17
Source File: LazySubscriberReferenceProvider.java    From idea-php-shopware-plugin with MIT License 4 votes vote down vote up
@Nullable
@Override
public PsiElement[] getGotoDeclarationTargets(@Nullable PsiElement psiElement, int i, Editor editor) {
    if(psiElement == null || !ShopwareProjectComponent.isValidForProject(psiElement)) {
        return new PsiElement[0];
    }

    PsiElement context = psiElement.getContext();
    if(!(context instanceof StringLiteralExpression)) {
        return new PsiElement[0];
    }

    String hookNameContent = null;

    ArrayCreationExpression arrayCreationExpression = PhpElementsUtil.getCompletableArrayCreationElement(context);
    if(arrayCreationExpression != null) {

        PsiElement returnStatement = arrayCreationExpression.getParent();
        if(returnStatement instanceof PhpReturn) {
            Method method = PsiTreeUtil.getParentOfType(returnStatement, Method.class);
            if(method != null) {
                if("getSubscribedEvents".equals(method.getName())) {
                    PhpClass phpClass = method.getContainingClass();
                    if(phpClass != null && PhpElementsUtil.isInstanceOf(phpClass, "\\Enlight\\Event\\SubscriberInterface")) {
                        hookNameContent = ((StringLiteralExpression) context).getContents();
                    }
                }
            }
        }

    } else  {

        MethodMatcher.MethodMatchParameter match = new MethodMatcher.StringParameterMatcher(context, 0)
            .withSignature("\\Shopware_Components_Plugin_Bootstrap", "subscribeEvent")
            .match();

        if(match == null) {
            return new PsiElement[0];
        }

        hookNameContent = ((StringLiteralExpression) context).getContents();
    }

    if(hookNameContent == null) {
        return new PsiElement[0];
    }

    return getHookTargets(psiElement.getProject(), hookNameContent);
}
 
Example 18
Source File: TwigVariablePathInspection.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
private boolean isWeakPhpClass(PhpNamedElement phpNamedElement) {
    return phpNamedElement instanceof PhpClass && (
        PhpElementsUtil.isInstanceOf((PhpClass) phpNamedElement, "ArrayAccess") ||
        PhpElementsUtil.isInstanceOf((PhpClass) phpNamedElement, "Iterator")
    );
}
 
Example 19
Source File: HookSubscriberUtil.java    From idea-php-shopware-plugin with MIT License 4 votes vote down vote up
public static void collectHooks(Project project, HookVisitor hookVisitor) {

        Collection<PhpClass> phpClasses = new ArrayList<>();

        // directly use core classes
        PhpIndex phpIndex = PhpIndex.getInstance(project);
        for(String coreClass: CORE_CLASSES) {
            phpClasses.addAll(phpIndex.getClassesByName(coreClass));
        }

        // fallback: search on directory
        VirtualFile virtualFile = VfsUtil.findRelativeFile(project.getBaseDir(), "engine", "core", "class");
        if(virtualFile != null) {
            for(VirtualFile coreClassFile: VfsUtil.getChildren(virtualFile)) {
                String name = coreClassFile.getName();
                if(name.contains(".")) name = name.substring(0, name.lastIndexOf('.'));
                if(!CORE_CLASSES.contains(name)) {
                    phpClasses.addAll(phpIndex.getClassesByName(name));
                }
            }
        }

        phpClasses.addAll(phpIndex.getAllSubclasses("\\Enlight_Hook"));

        for(PhpClass phpClass: phpClasses) {

            // dont use proxy classes
            String presentableFQN = phpClass.getPresentableFQN();
            if((presentableFQN.endsWith("Proxy") && PhpElementsUtil.isInstanceOf(phpClass, "\\Enlight_Hook_Proxy"))) {
                continue;
            }

            for(Method method: phpClass.getMethods()) {
                if(!method.getAccess().isPrivate() && !method.isStatic() && !method.isAbstract() && !method.getName().startsWith("_")) {
                    boolean returnValue = hookVisitor.visitHook(phpClass, method);
                    if(!returnValue) {
                        return;
                    }
                }
            }
        }

    }
 
Example 20
Source File: ServiceUtil.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
/**
 * Find every service tag that's implements or extends a classes/interface of give class
 */
@NotNull
public static Set<String> getPhpClassTags(@NotNull PhpClass phpClass) {
    Project project = phpClass.getProject();

    ContainerCollectionResolver.ServiceCollector collector = null;

    Set<String> matchedTags = new HashSet<>();
    Set<String> result = SymfonyProcessors.createResult(project, ServicesTagStubIndex.KEY);
    for (String serviceName : result) {

        // get service where we found our tags
        List<Set<String>> values = FileBasedIndex.getInstance().getValues(ServicesTagStubIndex.KEY, serviceName, GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(project), XmlFileType.INSTANCE, YAMLFileType.YML));
        if(values.size() == 0) {
            continue;
        }

        // create unique tag list
        Set<String> tags = new HashSet<>();
        for(Set<String> tagValue: values) {
            tags.addAll(tagValue);
        }

        if(collector == null) {
            collector = ContainerCollectionResolver.ServiceCollector.create(project);
        }

        PhpClass serviceClass = ServiceUtil.getServiceClass(project, serviceName, collector);
        if(serviceClass == null) {
            continue;
        }

        boolean matched = false;

        // get classes this service implements or extends
        for (PhpClass serviceClassImpl: getSuperClasses(serviceClass)) {
            // find interface or extends class which also implements
            // @TODO: currently first level only, check recursive
            if(!PhpElementsUtil.isEqualClassName(phpClass, serviceClassImpl) && PhpElementsUtil.isInstanceOf(phpClass, serviceClassImpl)) {
                matched = true;
                break;
            }
        }

        if(matched) {
            matchedTags.addAll(tags);
        }
    }

    return matchedTags;
}