Java Code Examples for com.jetbrains.php.lang.psi.elements.PhpClass#findMethodByName()

The following examples show how to use com.jetbrains.php.lang.psi.elements.PhpClass#findMethodByName() . 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: RouteHelperTest.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * @see fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper#convertMethodToRouteShortcutControllerName
 */
public void testConvertMethodToRouteShortcutControllerForInvoke()
{
    myFixture.configureFromExistingVirtualFile(myFixture.copyFileToProject("GetRoutesOnControllerAction.php"));

    PhpClass phpClass = PhpPsiElementFactory.createPhpPsiFromText(getProject(), PhpClass.class, "<?php\n" +
        "namespace FooBar\\FooBundle\\Controller" +
        "{\n" +
        "  class FooBarController\n" +
        "  {\n" +
        "     function __invoke() {}\n" +
        "  }\n" +
        "}"
    );

    Method fooAction = phpClass.findMethodByName("__invoke");
    assertNotNull(fooAction);

    assertEquals("FooBar\\FooBundle\\Controller\\FooBarController", RouteHelper.convertMethodToRouteShortcutControllerName(fooAction));
}
 
Example 2
Source File: Symfony2InterfacesUtil.java    From idea-php-toolbox with MIT License 6 votes vote down vote up
@NotNull
private Method[] getExpectedMethods(@NotNull Project project, @NotNull String ClassInterfaceName, @NotNull String methodName) {
    Set<Method> methods = new HashSet<>();

    for (PhpClass phpClass : PhpIndex.getInstance(project).getAnyByFQN(ClassInterfaceName)) {

        // handle constructor as string
        if(methodName.equalsIgnoreCase("__construct")) {
            Method constructor = phpClass.getConstructor();
            if(constructor != null) {
                methods.add(constructor);
            }
            continue;
        }

        Method method = phpClass.findMethodByName(methodName);
        if(method != null) {
            methods.add(method);
        }
    }
    
    return methods.toArray(new Method[methods.size()]);
}
 
Example 3
Source File: Symfony2InterfacesUtil.java    From idea-php-toolbox with MIT License 6 votes vote down vote up
@NotNull
private Method[] getExpectedMethods(@NotNull Project project, @NotNull String ClassInterfaceName, @NotNull String methodName) {
    Set<Method> methods = new HashSet<>();

    for (PhpClass phpClass : PhpIndex.getInstance(project).getAnyByFQN(ClassInterfaceName)) {

        // handle constructor as string
        if(methodName.equalsIgnoreCase("__construct")) {
            Method constructor = phpClass.getConstructor();
            if(constructor != null) {
                methods.add(constructor);
            }
            continue;
        }

        Method method = phpClass.findMethodByName(methodName);
        if(method != null) {
            methods.add(method);
        }
    }
    
    return methods.toArray(new Method[methods.size()]);
}
 
Example 4
Source File: ParameterResolverConsumer.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Override
public void consume(ParameterVisitor parameter) {
    PhpClass serviceClass = ServiceUtil.getResolvedClassDefinition(
        this.project,
        parameter.getClassName(),
        new ContainerCollectionResolver.LazyServiceCollector(this.project)
    );

    if(serviceClass == null) {
        return;
    }

    Method method = serviceClass.findMethodByName(parameter.getMethod());
    if (method == null) {
        return;
    }

    Parameter[] methodParameter = method.getParameters();
    if(parameter.getParameterIndex() >= methodParameter.length) {
        return;
    }

    consumer.consume(methodParameter[parameter.getParameterIndex()]);
}
 
Example 5
Source File: ControllerIndex.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Nullable
public ControllerAction getControllerActionOnService(String shortcutName) {

    // only foo_bar:Method is valid
    if(!RouteHelper.isServiceController(shortcutName)) {
        return null;
    }

    String serviceId = shortcutName.substring(0, shortcutName.lastIndexOf(":"));
    String methodName = shortcutName.substring(shortcutName.lastIndexOf(":") + 1);

    PhpClass phpClass = ServiceUtil.getResolvedClassDefinition(this.project, serviceId, getLazyServiceCollector(this.project));
    if(phpClass == null) {
        return null;
    }

    Method method = phpClass.findMethodByName(methodName);
    if(method == null) {
        return null;
    }

    return new ControllerAction(serviceId, method);
}
 
Example 6
Source File: FormFieldResolver.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private static void attachFormFields(@Nullable MethodReference methodReference, @NotNull Collection<TwigTypeContainer> targets) {
    if(methodReference != null && PhpElementsUtil.isMethodReferenceInstanceOf(
        methodReference,
        new MethodMatcher.CallToSignature("\\Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller", "createForm"),
        new MethodMatcher.CallToSignature("\\Symfony\\Bundle\\FrameworkBundle\\Controller\\ControllerTrait", "createForm"),
        new MethodMatcher.CallToSignature("\\Symfony\\Bundle\\FrameworkBundle\\Controller\\AbstractController", "createForm")
    )) {
        PsiElement formType = PsiElementUtils.getMethodParameterPsiElementAt(methodReference, 0);
        if(formType != null) {
            PhpClass phpClass = FormUtil.getFormTypeClassOnParameter(formType);

            if(phpClass == null) {
                return;
            }

            Method method = phpClass.findMethodByName("buildForm");
            if(method == null) {
                return;
            }

            targets.addAll(getTwigTypeContainer(method));
        }
    }
}
 
Example 7
Source File: XmlReferenceContributor.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement psiElement, @NotNull ProcessingContext processingContext) {
    if(!Symfony2ProjectComponent.isEnabled(psiElement) || !(psiElement instanceof XmlAttributeValue)) {
        return new PsiReference[0];
    }

    String method = ((XmlAttributeValue) psiElement).getValue();
    if(StringUtils.isBlank(method)) {
        return new PsiReference[0];
    }

    PhpClass phpClass = XmlHelper.getPhpClassForClassFactory((XmlAttributeValue) psiElement);
    if(phpClass == null) {
        return new PsiReference[0];
    }

    Method classMethod = phpClass.findMethodByName(method);
    if(classMethod == null) {
        return new PsiReference[0];
    }

    return new PsiReference[]{
        new ClassMethodStringPsiReference(psiElement, phpClass.getFQN(), classMethod.getName()),
    };
}
 
Example 8
Source File: EventMethodCallInspection.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private void registerMethodProblem(final @NotNull PsiElement psiElement, @NotNull ProblemsHolder holder, @Nullable PhpClass phpClass) {
    if(phpClass == null) {
        return;
    }

    final String methodName = PsiElementUtils.trimQuote(psiElement.getText());
    if(phpClass.findMethodByName(methodName) != null) {
        return;
    }

    holder.registerProblem(
        psiElement,
        "Missing Method",
        ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
        new CreateMethodQuickFix(phpClass, methodName, new MyCreateMethodQuickFix())
    );
}
 
Example 9
Source File: XmlReferenceContributor.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement psiElement, @NotNull ProcessingContext context) {
    if(!Symfony2ProjectComponent.isEnabled(psiElement) || !(psiElement instanceof XmlAttributeValue)) {
        return new PsiReference[0];
    }

    String method = ((XmlAttributeValue) psiElement).getValue();
    if(StringUtils.isBlank(method)) {
        return new PsiReference[0];
    }

    PhpClass phpClass = XmlHelper.getPhpClassForServiceFactory((XmlAttributeValue) psiElement);
    if(phpClass == null) {
        return new PsiReference[0];
    }

    Method targetMethod = phpClass.findMethodByName(method);
    if(targetMethod == null) {
        return new PsiReference[0];
    }

    return new PsiReference[] {
        new ClassMethodStringPsiReference(psiElement, phpClass.getFQN(), targetMethod.getName()),
    };
}
 
Example 10
Source File: YamlGoToDeclarationHandler.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
private Collection<PsiElement> getTagMethodGoto(@NotNull PsiElement psiElement) {
    String methodName = PsiElementUtils.trimQuote(psiElement.getText());
    if(StringUtils.isBlank(methodName)) {
        return Collections.emptyList();
    }

    String classValue = YamlHelper.getServiceDefinitionClassFromTagMethod(psiElement);
    if(classValue == null) {
        return Collections.emptyList();
    }

    PhpClass phpClass = ServiceUtil.getResolvedClassDefinition(psiElement.getProject(), classValue);
    if(phpClass == null) {
        return Collections.emptyList();
    }

    Method method = phpClass.findMethodByName(methodName);
    if(method != null) {
        return Collections.singletonList(method);
    }

    return Collections.emptyList();
}
 
Example 11
Source File: PhpElementsUtil.java    From intellij-neos with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
static public Method getClassMethod(@NotNull Project project, @NotNull String phpClassName, @NotNull String methodName) {
    // we need here an each; because eg Command is non unique because of phar file
    for(PhpClass phpClass: PhpIndex.getInstance(project).getClassesByFQN(phpClassName)) {
        NeosProjectService.getLogger().debug(phpClass.getFQN());
        Method method = phpClass.findMethodByName(methodName);
        if(method != null) {
            return method;
        }
    }

    return null;
}
 
Example 12
Source File: RouteHelperTest.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * @see fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper#convertMethodToRouteShortcutControllerName
 */
public void testConvertMethodToRouteShortcutControllerName() {
    myFixture.configureFromExistingVirtualFile(myFixture.copyFileToProject("GetRoutesOnControllerAction.php"));

    PhpClass phpClass = PhpPsiElementFactory.createPhpPsiFromText(getProject(), PhpClass.class, "<?php\n" +
        "namespace FooBar\\FooBundle\\Controller" +
        "{\n" +
        "  class FooBarController\n" +
        "  {\n" +
        "     function fooAction() {}\n" +
        "  }\n" +
        "}"
    );

    Method fooAction = phpClass.findMethodByName("fooAction");
    assertNotNull(fooAction);

    assertEquals("FooBarFooBundle:FooBar:foo", RouteHelper.convertMethodToRouteShortcutControllerName(fooAction));

    phpClass = PhpPsiElementFactory.createPhpPsiFromText(getProject(), PhpClass.class, "<?php\n" +
        "namespace FooBar\\FooBundle\\Controller\\SubFolder" +
        "{\n" +
        "  class SubController\n" +
        "  {\n" +
        "     function fooAction() {}\n" +
        "  }\n" +
        "}"
    );

    fooAction = phpClass.findMethodByName("fooAction");
    assertNotNull(fooAction);

    assertEquals("FooBarFooBundle:SubFolder\\Sub:foo", RouteHelper.convertMethodToRouteShortcutControllerName(fooAction));
}
 
Example 13
Source File: ClassPublicMethodReference.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public ResolveResult[] multiResolve(boolean incompleteCode) {
    PhpClass phpClass = ServiceUtil.getResolvedClassDefinition(getElement().getProject(), this.className);
    if(phpClass == null) {
        return new ResolveResult[0];
    }

    Method targetMethod = phpClass.findMethodByName(this.method);
    if(targetMethod == null) {
        return new ResolveResult[0];
    }

    return PsiElementResolveResult.createResults(targetMethod);
}
 
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: 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: ServiceRouteContainer.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@NotNull
public Collection<Route> getMethodMatches(@NotNull Method method) {
    PhpClass originClass = method.getContainingClass();
    if(originClass == null) {
        return Collections.emptyList();
    }

    String classFqn = StringUtils.stripStart(originClass.getFQN(), "\\");

    Collection<Route> routes = new ArrayList<>();
    for (Route route : this.routes) {

        String serviceRoute = route.getController();
        if(serviceRoute == null) {
            continue;
        }

        // if controller matches:
        // service_id:methodName
        String[] split = serviceRoute.split(":");
        if(split.length != 2 || !split[1].equals(method.getName())) {
            continue;
        }

        // cache PhpClass resolve
        if(!serviceCache.containsKey(split[0])) {
            serviceCache.put(split[0], ServiceUtil.getResolvedClassDefinition(method.getProject(), split[0], getLazyServiceCollector(method.getProject())));
        }

        PhpClass phpClass = serviceCache.get(split[0]);
        if(phpClass != null && classFqn.equals(phpClass.getPresentableFQN())) {
            Method targetMethod = phpClass.findMethodByName(split[1]);
            if(targetMethod != null) {
                routes.add(route);
            }
        }
    }

    return routes;
}
 
Example 17
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 18
Source File: FluidTypeResolver.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@NotNull
private static Set<String> collectIteratorReturns(@NotNull PsiElement psiElement, @NotNull Set<String> types) {
    Set<String> arrayValues = new HashSet<>();
    for (String type : types) {
        PhpClass phpClass = 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 19
Source File: ControllerIndex.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
@NotNull
public Collection<Method> resolveShortcutName(@NotNull String controllerName) {
    String[] split = controllerName.split(":");

    // normalize: "FooBundle:Apple/Bar:foo" => FooBundle:Apple\Bar:foo
    // support: "FooBundle:Apple\Bar:foo" => FooBundle:Apple\Bar:foo\bar
    if(split.length == 3) {
        // normalize incoming path "/" => "\" this are PHP namespace but both supported
        split[1] = split[1].replaceAll("/+", "\\\\").replaceAll("\\\\+", "\\\\");
        split[2] = split[2].replaceAll("/+", "\\\\").replaceAll("\\\\+", "\\\\");

        Collection<Method> methods = new HashSet<>();
        for (SymfonyBundle symfonyBundle : new SymfonyBundleUtil(project).getBundles()) {
            // Bundle matched "AppBundle"
            if(split[0].equalsIgnoreCase(symfonyBundle.getName())) {
                String namespace = split[1] + "\\" + split[2];

                // last element is our method name
                int lastBackslash = namespace.lastIndexOf("\\");
                if(lastBackslash > 0) {
                    String methodName = namespace.substring(lastBackslash + 1);

                    // AppBundle/Controller/FooController
                    String className = symfonyBundle.getNamespaceName() + "Controller\\" + namespace.substring(0, lastBackslash) + "Controller";

                    for (PhpClass phpClass : PhpElementsUtil.getClassesInterface(project, className)) {

                        // cleanup action to support "fooAction" and "foo" methods
                        if(methodName.endsWith("Action")) {
                            methodName = methodName.substring(0, methodName.length() - "Action".length());
                        }

                        // find method
                        for (String string : new String[] {methodName, methodName + "Action"}) {
                            Method methodByName = phpClass.findMethodByName(string);
                            if(methodByName != null) {
                                methods.add(methodByName);
                            }
                        }
                    }
                }
            }
        }

        return methods;
    }

    ControllerAction controllerAction = new ControllerIndex(project).getControllerActionOnService(controllerName);
    if(controllerAction != null) {
        return Collections.singletonList(controllerAction.getMethod());
    }

    return Collections.emptyList();
}
 
Example 20
Source File: RouteHelperTest.java    From idea-php-symfony2-plugin with MIT License 4 votes vote down vote up
/**
 * @see fr.adrienbrault.idea.symfony2plugin.routing.RouteHelper#getRoutesOnControllerAction
 */
public void testGetRoutesOnControllerAction() {
    myFixture.copyFileToProject("GetRoutesOnControllerAction.php");
    myFixture.copyFileToProject("GetRoutesOnControllerAction.routing.xml");
    myFixture.copyFileToProject("GetRoutesOnControllerAction.services.xml");

    PhpClass phpClass = PhpPsiElementFactory.createPhpPsiFromText(getProject(), PhpClass.class, "<?php\n" +
        "namespace FooBar\\FooBundle\\Controller\\SubFolder" +
        "{\n" +
        "  class FooBarController\n" +
        "  {\n" +
        "     function fooAction() {}\n" +
        "  }\n" +
        "}"
    );

    Method fooAction = phpClass.findMethodByName("fooAction");
    assertNotNull(fooAction);

    List<Route> routesOnControllerAction = RouteHelper.getRoutesOnControllerAction(fooAction);

    assertNotNull(ContainerUtil.find(routesOnControllerAction, route ->
        "xml_route_subfolder_backslash".equals(route.getName())
    ));

    assertNotNull(ContainerUtil.find(routesOnControllerAction, route ->
        "xml_route_subfolder_slash".equals(route.getName())
    ));

    assertNotNull(ContainerUtil.find(routesOnControllerAction, route ->
        "xml_route_subfolder_class_syntax".equals(route.getName())
    ));

    // controller as service
    Method indexAction = PhpElementsUtil.getClassMethod(getProject(), "Service\\Controller\\FooController", "indexAction");
    assertNotNull(indexAction);

    assertNotNull(ContainerUtil.find(RouteHelper.getRoutesOnControllerAction(indexAction), route ->
        "xml_route_as_service".equals(route.getName())
    ));
}