fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil Java Examples

The following examples show how to use fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil. 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: 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 #2
Source File: PhpElementsUtilTest.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * @see fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil#getVariableReferencesInScope
 */
public void testGetVariableReferencesInScopeForVariable() {
    myFixture.configureByText(PhpFileType.INSTANCE, "<?php\n" +
        "function foobar() {\n" +
        "  $var = new \\DateTime();" +
        "  $va<caret>r->format();" +
        "  $var->modify();" +
        "\n}"
    );

    PsiElement psiElement = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
    assertNotNull(psiElement);

    Collection<Variable> vars = PhpElementsUtil.getVariableReferencesInScope((Variable) psiElement.getParent());
    assertSize(2, vars);

    assertNotNull(ContainerUtil.find(vars, variable ->
        "$var = new \\DateTime()".equals(variable.getParent().getText()))
    );

    assertNotNull(ContainerUtil.find(vars, variable ->
        "$var->modify()".equals(variable.getParent().getText()))
    );
}
 
Example #3
Source File: PhpElementsUtilTest.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * @see fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil#getParameterListArrayValuePattern
 */
public void testGetParameterListArrayValuePattern() {
    String[] strings = {
        "foo(['<caret>']",
        "foo(['<caret>' => 'foo']",
        "foo(['foo' => null, '<caret>' => null]"
    };

    for (String s : strings) {
        myFixture.configureByText(PhpFileType.INSTANCE, "<?php\n" + s);

        assertTrue(
            PhpElementsUtil.getParameterListArrayValuePattern().accepts(myFixture.getFile().findElementAt(myFixture.getCaretOffset()))
        );
    }

    myFixture.configureByText(PhpFileType.INSTANCE, "<?php\n" +
        "foobar(['foobar' => '<caret>'])"
    );

    assertFalse(
        PhpElementsUtil.getParameterListArrayValuePattern().accepts(myFixture.getFile().findElementAt(myFixture.getCaretOffset()))
    );
}
 
Example #4
Source File: YamlCompletionContributor.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
    if(!Symfony2ProjectComponent.isEnabled(completionParameters.getPosition())) {
        return;
    }

    PsiElement psiElement = completionParameters.getPosition();

    String serviceDefinitionClassFromTagMethod = YamlHelper.getServiceDefinitionClassFromTagMethod(psiElement);

    if(serviceDefinitionClassFromTagMethod != null) {
        PhpClass phpClass = ServiceUtil.getResolvedClassDefinition(psiElement.getProject(), serviceDefinitionClassFromTagMethod);
        if(phpClass != null) {
            PhpElementsUtil.addClassPublicMethodCompletion(completionResultSet, phpClass);
        }
    }
}
 
Example #5
Source File: JavascriptServiceNameStrategy.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Nullable
public static Object run(@NotNull Project project, @NotNull String className, @NotNull String serviceJsNameStrategy) throws ScriptException {

    JsonObject jsonObject = new JsonObject();

    jsonObject.addProperty("className", className);
    jsonObject.addProperty("projectName", project.getName());
    jsonObject.addProperty("projectBasePath", project.getBasePath());
    jsonObject.addProperty("defaultNaming", new DefaultServiceNameStrategy().getServiceName(new ServiceNameStrategyParameter(project, className)));

    PhpClass aClass = PhpElementsUtil.getClass(project, className);
    if(aClass != null) {
        String relativePath = VfsUtil.getRelativePath(aClass.getContainingFile().getVirtualFile(), ProjectUtil.getProjectDir(aClass), '/');
        if(relativePath != null) {
            jsonObject.addProperty("relativePath", relativePath);
        }
        jsonObject.addProperty("absolutePath", aClass.getContainingFile().getVirtualFile().toString());
    }

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
    if(engine == null) {
        return null;
    }

    return engine.eval("var __p = eval(" + jsonObject.toString() + "); result = function(args) { " + serviceJsNameStrategy + " }(__p)");
}
 
Example #6
Source File: XmlHelper.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * Get class factory method attribute
 *
 * <factory class="FooBar" method="cre<caret>ate"/>
 */
@Nullable
public static PhpClass getPhpClassForClassFactory(@NotNull XmlAttributeValue xmlAttributeValue) {
    String method = xmlAttributeValue.getValue();
    if(StringUtils.isBlank(method)) {
        return null;
    }

    XmlTag parentOfType = PsiTreeUtil.getParentOfType(xmlAttributeValue, XmlTag.class);
    if(parentOfType == null) {
        return null;
    }

    String aClass = parentOfType.getAttributeValue("class");
    if(aClass == null || StringUtils.isBlank(aClass)) {
        return null;
    }

    return PhpElementsUtil.getClass(xmlAttributeValue.getProject(), aClass);
}
 
Example #7
Source File: FormGotoCompletionRegistrar.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
private String extractTranslationDomainFromScope(@NotNull ArrayCreationExpression arrayCreation) {
    String domain = "messages";
    PhpPsiElement value = PhpElementsUtil.getArrayValue(arrayCreation, "choice_translation_domain");

    if(value instanceof StringLiteralExpression) {
        String contents = PhpElementsUtil.getStringValue(value);
        if(contents != null) {
            domain = contents;
        }
    } else {
        // translation_domain in current array block
        String translationDomain = FormOptionsUtil.getTranslationFromScope(arrayCreation);
        if(translationDomain != null) {
            domain = translationDomain;
        }
    }

    return domain;
}
 
Example #8
Source File: CreateMethodQuickFix.java    From idea-php-shopware-plugin with MIT License 6 votes vote down vote up
private void attachVariablesInScope(@NotNull Project project, StringBuilder stringBuilder) {

        // Events
        if(HookSubscriberUtil.NOTIFY_EVENTS_MAP.containsKey(generatorContainer.getHookName())) {
            Collection<String> references = HookSubscriberUtil.NOTIFY_EVENTS_MAP.get(generatorContainer.getHookName());
            for (String value : references) {
                String[] split = value.split("\\.");
                Method classMethod = PhpElementsUtil.getClassMethod(project, split[0], split[1]);
                if(classMethod == null) {
                    continue;
                }

                buildEventVariables(project, stringBuilder, classMethod);
            }
        } else if(generatorContainer.getHookMethod() != null) {
            // add hook parameter
            Parameter[] hookMethodParameters = generatorContainer.getHookMethod().getParameters();
            if(hookMethodParameters.length > 0 ) {
                stringBuilder.append("\n");
                for(Parameter parameter : hookMethodParameters) {
                    String name = parameter.getName();
                    stringBuilder.append("$").append(name).append(" = ").append("$args->get('").append(name).append("');\n");
                }
            }
        }
    }
 
Example #9
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 #10
Source File: ServiceUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * Resolve "@service" to its class + proxy ServiceCollector for iteration
 */
@Nullable
public static PhpClass getServiceClass(@NotNull Project project, @NotNull String serviceName, @NotNull ContainerCollectionResolver.ServiceCollector collector) {

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

    String resolve = collector.resolve(serviceName);
    if(resolve == null) {
        return null;
    }

    return PhpElementsUtil.getClassInterface(project, resolve);
}
 
Example #11
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 #12
Source File: YamlGoToDeclarationHandler.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
private Collection<PsiElement> classGoToDeclaration(@NotNull PsiElement psiElement, @NotNull String className) {

    Collection<PsiElement> psiElements = new HashSet<>();

    // Class::method
    // Class::FooAction
    // Class:Foo
    if(className.contains(":")) {
        String[] split = className.replaceAll("(:)\\1", "$1").split(":");
        if(split.length == 2) {
            for(String append: new String[] {"", "Action"}) {
                Method classMethod = PhpElementsUtil.getClassMethod(psiElement.getProject(), split[0], split[1] + append);
                if(classMethod != null) {
                    psiElements.add(classMethod);
                }
            }
        }

        return psiElements;
    }

    // ClassName
    psiElements.addAll(PhpElementsUtil.getClassesInterface(psiElement.getProject(), className));
    return psiElements;
}
 
Example #13
Source File: ServiceDeprecatedClassesInspection.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Override
public void visitElement(PsiElement element) {
    MethodReference methodReference = PsiElementUtils.getMethodReferenceWithFirstStringParameter(element);
    if (methodReference == null || !PhpElementsUtil.isMethodReferenceInstanceOf(methodReference, ServiceContainerUtil.SERVICE_GET_SIGNATURES)) {
        super.visitElement(element);
        return;
    }

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

    String contents = ((StringLiteralExpression) psiElement).getContents();
    if(StringUtils.isNotBlank(contents)) {
        this.problemRegistrar.attachDeprecatedProblem(element, contents, holder);
        this.problemRegistrar.attachServiceDeprecatedProblem(element, contents, holder);
    }

    super.visitElement(element);
}
 
Example #14
Source File: ObjectRepositoryTypeProvider.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Nullable
@Override
public PhpType getType(PsiElement e) {
    if (!Settings.getInstance(e.getProject()).pluginEnabled) {
        return null;
    }

    if(!(e instanceof MethodReference) || !PhpElementsUtil.isMethodWithFirstStringOrFieldReference(e, "getRepository")) {
        return null;
    }


    String refSignature = ((MethodReference)e).getSignature();
    if(StringUtil.isEmpty(refSignature)) {
        return null;
    }

    String signature = PhpTypeProviderUtil.getReferenceSignatureByFirstParameter((MethodReference) e, TRIM_KEY);
    return signature == null ? null : new PhpType().add("#" + this.getKey() + signature);
}
 
Example #15
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 #16
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 #17
Source File: FormOptionsUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
private static Set<PhpClass> getFormTypeExtensionClassNames(@NotNull Project project) {

    Set<PhpClass> phpClasses = new HashSet<>();

    // @TODO: should be same as interface?
    for (String s : ServiceXmlParserFactory.getInstance(project, FormExtensionServiceParser.class).getFormExtensions().keySet()) {
        ContainerUtil.addIfNotNull(
            phpClasses,
            PhpElementsUtil.getClass(project, s)
        );
    }

    for(PhpClass phpClass: PhpIndex.getInstance(project).getAllSubclasses(FormUtil.FORM_EXTENSION_INTERFACE)) {
        if(!FormUtil.isValidFormPhpClass(phpClass)) {
            continue;
        }

        phpClasses.add(phpClass);
    }

    return phpClasses;
}
 
Example #18
Source File: TwigTypeResolveUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
public static String getTypeDisplayName(Project project, Set<String> types) {

        Collection<PhpClass> classFromPhpTypeSet = PhpElementsUtil.getClassFromPhpTypeSet(project, types);
        if(classFromPhpTypeSet.size() > 0) {
            return classFromPhpTypeSet.iterator().next().getPresentableFQN();
        }

        PhpType phpType = new PhpType();
        for (String type : types) {
            phpType.add(type);
        }
        PhpType phpTypeFormatted = PhpIndex.getInstance(project).completeType(project, phpType, new HashSet<>());

        if(phpTypeFormatted.getTypes().size() > 0) {
            return StringUtils.join(phpTypeFormatted.getTypes(), "|");
        }

        if(types.size() > 0) {
            return types.iterator().next();
        }

        return "";

    }
 
Example #19
Source File: FormOptionGotoCompletionRegistrar.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Nullable
@Override
public GotoCompletionProvider getProvider(@NotNull PsiElement psiElement) {
    if (!Symfony2ProjectComponent.isEnabled(psiElement)) {
        return null;
    }

    ArrayCreationExpression arrayCreationExpression = PhpElementsUtil.getCompletableArrayCreationElement(psiElement.getParent());
    if(arrayCreationExpression != null) {
        PsiElement parameterList = arrayCreationExpression.getParent();
        if (parameterList instanceof ParameterList) {
            PsiElement context = parameterList.getContext();
            if(context instanceof MethodReference) {
                ParameterBag currentIndex = PsiElementUtils.getCurrentParameterIndex(arrayCreationExpression);
                if(currentIndex != null && currentIndex.getIndex() == 2) {
                    if (PhpElementsUtil.isMethodReferenceInstanceOf((MethodReference) context, FormUtil.PHP_FORM_BUILDER_SIGNATURES)) {
                        return getMatchingOption((ParameterList) parameterList, psiElement);
                    }
                }
            }
        }
    }

    return null;
}
 
Example #20
Source File: EventDispatcherSubscriberUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
private static Collection<EventDispatcherSubscribedEvent> getSubscribedEventsProxy(@NotNull Project project) {

    Collection<EventDispatcherSubscribedEvent> events = new ArrayList<>();

    // http://symfony.com/doc/current/components/event_dispatcher/introduction.html
    PhpIndex phpIndex = PhpIndex.getInstance(project);
    Collection<PhpClass> phpClasses = phpIndex.getAllSubclasses("\\Symfony\\Component\\EventDispatcher\\EventSubscriberInterface");

    for(PhpClass phpClass: phpClasses) {

        if(PhpElementsUtil.isTestClass(phpClass)) {
            continue;
        }

        Method method = phpClass.findMethodByName("getSubscribedEvents");
        if(method != null) {
            PhpReturn phpReturn = PsiTreeUtil.findChildOfType(method, PhpReturn.class);
            if(phpReturn != null) {
                attachSubscriberEventNames(events, phpClass, phpReturn);
            }
        }
    }

   return events;
}
 
Example #21
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 #22
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 #23
Source File: PhpElementsUtilTest.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * @see fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil#getFirstVariableTypeInScope(Variable)
 */
public void testGetFirstVariableTypeInScope() {
    PsiElement psiElement = myFixture.configureByText(PhpFileType.INSTANCE, "<?php" +
        "$foo = new \\DateTime();\n" +
        "$d->dispatch('foo', $f<caret>oo)->;").findElementAt(myFixture.getCaretOffset()).getParent();

    assertEquals("\\DateTime", PhpElementsUtil.getFirstVariableTypeInScope((Variable) psiElement));

    psiElement = myFixture.configureByText(PhpFileType.INSTANCE, "<?php" +
        "function foo() {" +
        "  $foo = new \\DateTime();\n" +
        "  $d->dispatch('foo', $f<caret>oo);\n" +
        "}").findElementAt(myFixture.getCaretOffset()).getParent();

    assertEquals("\\DateTime", PhpElementsUtil.getFirstVariableTypeInScope((Variable) psiElement));
}
 
Example #24
Source File: CaseSensitivityServiceInspection.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private void phpVisitor(final @NotNull ProblemsHolder holder, @NotNull PsiFile psiFile) {

        psiFile.acceptChildren(new PsiRecursiveElementVisitor() {
            @Override
            public void visitElement(PsiElement element) {
                PsiElement parent = element.getParent();
                if(!(parent instanceof StringLiteralExpression)) {
                    super.visitElement(element);
                    return;
                }

                MethodReference methodReference = PsiElementUtils.getMethodReferenceWithFirstStringParameter(element);
                if (methodReference != null && PhpElementsUtil.isMethodReferenceInstanceOf(methodReference, ServiceContainerUtil.SERVICE_GET_SIGNATURES)) {
                    String serviceName = ((StringLiteralExpression) parent).getContents();
                    if(StringUtils.isNotBlank(serviceName) && !serviceName.equals(serviceName.toLowerCase())) {
                        holder.registerProblem(element, SYMFONY_LOWERCASE_LETTERS_FOR_SERVICE, ProblemHighlightType.WEAK_WARNING);
                    }
                }

                super.visitElement(element);
            }
        });
    }
 
Example #25
Source File: PhpTranslationDomainInspection.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private void invoke(@NotNull ProblemsHolder holder, @NotNull PsiElement psiElement) {
    if (!(psiElement instanceof StringLiteralExpression) || !(psiElement.getContext() instanceof ParameterList)) {
        return;
    }

    ParameterList parameterList = (ParameterList) psiElement.getContext();

    PsiElement methodReference = parameterList.getContext();
    if (!(methodReference instanceof MethodReference)) {
        return;
    }

    if (!PhpElementsUtil.isMethodReferenceInstanceOf((MethodReference) methodReference, TranslationUtil.PHP_TRANSLATION_SIGNATURES)) {
        return;
    }

    int domainParameter = 2;
    if("transChoice".equals(((MethodReference) methodReference).getName())) {
        domainParameter = 3;
    }

    ParameterBag currentIndex = PsiElementUtils.getCurrentParameterIndex(psiElement);
    if(currentIndex != null && currentIndex.getIndex() == domainParameter) {
        annotateTranslationDomain((StringLiteralExpression) psiElement, holder);
    }
}
 
Example #26
Source File: DoctrineRepositoryClassConstantIntention.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement psiElement) throws IncorrectOperationException {
    PsiElement parent = psiElement.getParent();
    if(!(parent instanceof StringLiteralExpression)) {
        return;
    }

    try {
        PhpClass phpClass = EntityHelper.resolveShortcutName(project, ((StringLiteralExpression) parent).getContents());
        if(phpClass == null) {
            throw new Exception("Can not resolve model class");
        }
        PhpElementsUtil.replaceElementWithClassConstant(phpClass, parent);
    } catch (Exception e) {
        HintManager.getInstance().showErrorHint(editor, e.getMessage());
    }
}
 
Example #27
Source File: TwigExtensionParser.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * Add needs_environment, needs_context values to twig extension object
 */
static private Map<String, String> getOptions(@NotNull ArrayCreationExpression arrayCreationExpression) {
    Map<String, String> options = new HashMap<>();

    for(String optionTrue: new String[] {"needs_environment", "needs_context"}) {
        PhpPsiElement phpPsiElement = PhpElementsUtil.getArrayValue(arrayCreationExpression, optionTrue);
        if(phpPsiElement instanceof ConstantReference) {
            String value = phpPsiElement.getName();
            if(value != null && value.toLowerCase().equals("true")) {
                options.put(optionTrue, "true");
            }
        }
    }

    return options;
}
 
Example #28
Source File: DoctrineMetadataUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * Try to find repository class on models scope on its metadata definition
 */
@Nullable
public static PhpClass getClassRepository(final @NotNull Project project, final @NotNull String className) {

    for (VirtualFile virtualFile : FileBasedIndex.getInstance().getContainingFiles(DoctrineMetadataFileStubIndex.KEY, className, GlobalSearchScope.allScope(project))) {

        final String[] phpClass = {null};

        FileBasedIndex.getInstance().processValues(DoctrineMetadataFileStubIndex.KEY, className, virtualFile, (virtualFile1, model) -> {
            if (phpClass[0] != null  || model == null || model.getRepositoryClass() == null) {
                return true;
            }

            // piping value out of this index thread
            phpClass[0] = model.getRepositoryClass();

            return true;
        }, GlobalSearchScope.allScope(project));

        if(phpClass[0] != null) {
            return PhpElementsUtil.getClassInsideNamespaceScope(project, className, phpClass[0]);
        }
    }

    return null;
}
 
Example #29
Source File: PhpMessageSubscriberGotoCompletionRegistrar.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Override
public void register(@NotNull GotoCompletionRegistrarParameter registrar) {
    registrar.register(REGISTRAR_PATTERN, psiElement -> {
        Method method = PsiTreeUtil.getParentOfType(psiElement, Method.class, true, Function.class);

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

        if (!PhpElementsUtil.isMethodInstanceOf(method, "\\Symfony\\Component\\Messenger\\Handler\\MessageSubscriberInterface", "getHandledMessages")) {
            return null;
        }

        return new PhpClassPublicMethodProvider(method.getContainingClass());
    });
}
 
Example #30
Source File: DoctrineTypeGotoCompletionRegistrar.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {
    String modelNameInScope = DoctrineMetadataUtil.findModelNameInScope(getElement());
    if(modelNameInScope == null) {
        return Collections.emptyList();
    }

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

    Collection<LookupElement> lookupElements = new ArrayList<>();
    for (PhpClass phpClass : PhpElementsUtil.getClassesInterface(getProject(), modelNameInScope)) {
        for (Field field : phpClass.getFields()) {
            if(field.isConstant() || unique.contains(field.getName())) {
                continue;
            }

            String name = field.getName();
            unique.add(name);
            lookupElements.add(LookupElementBuilder.create(name).withIcon(field.getIcon()).withTypeText(phpClass.getPresentableFQN(), true));
        }
    }

    return lookupElements;
}