Java Code Examples for com.intellij.psi.xml.XmlTag

The following are top voted examples for showing how to use com.intellij.psi.xml.XmlTag. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: AppleScript-IDEA   File: DictionaryClass.java   Source Code and License 6 votes vote down vote up
public DictionaryClass(@NotNull Suite suite, @NotNull String name, @NotNull String code,
                       @NotNull XmlTag xmlTagClass, @Nullable String parentClassName,
                       @Nullable List<String> elementNames, @Nullable List<String> respondingCommandNames,
                       @Nullable String pluralClassName) {
  super(suite, name, code, xmlTagClass, null);
  this.parentClassName = parentClassName;
  this.pluralClassName = StringUtil.isEmpty(pluralClassName) ? name + "s" : pluralClassName;
  if (elementNames != null) {
    this.elementNames = elementNames;
  } else {
    this.elementNames = new ArrayList<>();
  }
  if (respondingCommandNames != null) {
    this.respondingCommandNames = respondingCommandNames;
  } else {
    this.respondingCommandNames = new ArrayList<>();
  }
}
 
Example 2
Project: idea-php-typo3-plugin   File: TranslationReferenceTest.java   Source Code and License 6 votes vote down vote up
public void testReferenceCanResolveDefinition() {
    PsiFile file = myFixture.configureByText(PhpFileType.INSTANCE, "<?php \n" +
            "\"LLL:EXT:foo/sample.xlf:sys_<caret>language.language_isocode.ab\";");

    PsiElement elementAtCaret = file.findElementAt(myFixture.getCaretOffset()).getParent();
    PsiReference[] references = elementAtCaret.getReferences();
    for (PsiReference reference : references) {
        if (reference instanceof TranslationReference) {
            ResolveResult[] resolveResults = ((TranslationReference) reference).multiResolve(false);
            for (ResolveResult resolveResult : resolveResults) {
                assertInstanceOf(resolveResult.getElement(), XmlTag.class);

                return;
            }
        }
    }

    fail("No TranslationReference found");
}
 
Example 3
Project: magento2-phpstorm-plugin   File: LayoutIndex.java   Source Code and License 6 votes vote down vote up
private static List<XmlTag> getComponentDeclarations(String componentValue, String componentType, ID<String, Void> id, Project project, ComponentMatcher componentMatcher) {
    List<XmlTag> results = new ArrayList<XmlTag>();
    Collection<VirtualFile> containingFiles = FileBasedIndex.getInstance()
        .getContainingFiles(
            id,
            componentValue,
            GlobalSearchScope.allScope(project)
        );
    PsiManager psiManager = PsiManager.getInstance(project);

    for (VirtualFile virtualFile: containingFiles) {
        XmlFile xmlFile = (XmlFile)psiManager.findFile(virtualFile);
        if (xmlFile == null) {
            continue;
        }

        XmlTag rootTag = xmlFile.getRootTag();
        if (rootTag == null) {
            continue;
        }
        collectComponentDeclarations(rootTag, results, componentValue, componentType, componentMatcher);
    }

    return results;
}
 
Example 4
Project: magento2-phpstorm-plugin   File: TypeConfigurationIndex.java   Source Code and License 6 votes vote down vote up
public static List<XmlTag> getClassConfigurations(PhpClass phpClass) {
    String classFqn = phpClass.getPresentableFQN();

    Collection<VirtualFile> containingFiles = FileBasedIndex.getInstance()
        .getContainingFiles(KEY, classFqn, GlobalSearchScope.allScope(phpClass.getProject())
    );

    PsiManager psiManager = PsiManager.getInstance(phpClass.getProject());

    List<XmlTag> tags = new ArrayList<XmlTag>();

    for (VirtualFile virtualFile: containingFiles) {
        XmlFile file = (XmlFile)psiManager.findFile(virtualFile);

        if (file == null) {
            continue;
        }

        XmlTag rootTag = file.getRootTag();
        fillRelatedTags(classFqn, rootTag, tags);
    }

    return tags;
}
 
Example 5
Project: magento2-phpstorm-plugin   File: TypeConfigurationIndex.java   Source Code and License 6 votes vote down vote up
private static void fillRelatedTags(String classFqn, XmlTag parentTag, List<XmlTag> tagsReferences) {
    for (XmlTag childTag: parentTag.getSubTags()) {
        String tagName = childTag.getName();
        String attribute = TAG_ATTRIBUTE_RELATION.get(tagName);
        if (attribute != null) {
            String className = childTag.getAttributeValue(attribute);
            if (className != null && PhpLangUtil.toPresentableFQN(className).equals(classFqn)) {
                tagsReferences.add(getLineMarkerDecorator(childTag));
            }
        }

        // type tag has plugin tags
        if (tagName.equals(TYPE_TAG)) {
            fillRelatedTags(classFqn, childTag, tagsReferences);
        }

        if (tagName.equals("event")) {
            fillRelatedTags(classFqn, childTag, tagsReferences);
        }
    }
}
 
Example 6
Project: magento2-phpstorm-plugin   File: TypeConfigurationIndex.java   Source Code and License 6 votes vote down vote up
/**
 * Decorate tag with appropriate line marker decorator.
 */
@NotNull
private static XmlTag getLineMarkerDecorator(XmlTag tag) {
    switch (tag.getName()) {
        case PREFERENCE_TAG:
            return new DiPreferenceLineMarkerXmlTagDecorator(tag);
        case TYPE_TAG:
            return new DiTypeLineMarkerXmlTagDecorator(tag);
        case PLUGIN_TAG:
            return new DiPluginLineMarkerXmlTagDecorator(tag);
        case VIRTUAL_TYPE_TAG:
            return new DiVirtualTypeLineMarkerXmlTagDecorator(tag);
        default:
            return tag;
    }
}
 
Example 7
Project: magento2-phpstorm-plugin   File: WebApiTypeIndex.java   Source Code and License 6 votes vote down vote up
/**
 * Get list of Web API routes associated with the provided method.
 *
 * Parent classes are not taken into account.
 */
public static List<XmlTag> getWebApiRoutes(Method method) {
    List<XmlTag> tags = new ArrayList<>();
    if (!method.getAccess().isPublic()) {
        return tags;
    }
    PhpClass phpClass = method.getContainingClass();
    String methodFqn = method.getName();
    if (phpClass == null) {
        return tags;
    }
    String classFqn = phpClass.getPresentableFQN();
    Collection<VirtualFile> containingFiles = FileBasedIndex
        .getInstance().getContainingFiles(KEY, classFqn, GlobalSearchScope.allScope(phpClass.getProject()));

    PsiManager psiManager = PsiManager.getInstance(phpClass.getProject());
    for (VirtualFile virtualFile : containingFiles) {
        XmlFile file = (XmlFile) psiManager.findFile(virtualFile);
        if (file == null) {
            continue;
        }
        XmlTag rootTag = file.getRootTag();
        fillRelatedTags(classFqn, methodFqn, rootTag, tags);
    }
    return tags;
}
 
Example 8
Project: magento2-phpstorm-plugin   File: MagentoComponentManager.java   Source Code and License 6 votes vote down vote up
@Override
public String getMagentoName() {
    if (moduleName != null) {
        return moduleName;
    }

    PsiDirectory configurationDir = directory.findSubdirectory(CONFIGURATION_PATH);
    if (configurationDir != null) {
        PsiFile configurationFile = configurationDir.findFile("module.xml");

        if (configurationFile != null && configurationFile instanceof XmlFile) {
            XmlTag rootTag = ((XmlFile) configurationFile).getRootTag();
            if (rootTag != null) {
                XmlTag module = rootTag.findFirstSubTag("module");
                if (module != null && module.getAttributeValue("name") != null) {
                    moduleName = module.getAttributeValue("name");
                    return moduleName;
                }
            }
        }
    }

    return DEFAULT_MODULE_NAME;
}
 
Example 9
Project: magento2-phpstorm-plugin   File: WebApiLineMarkerProvider.java   Source Code and License 6 votes vote down vote up
/**
 * Get list of Web API routes related to the specified method.
 * <p/>
 * Web API declarations for parent classes are taken into account.
 * Results are not cached.
 */
List<XmlTag> extractRoutesForMethod(@NotNull Method method) {
    List<XmlTag> routesForMethod = WebApiTypeIndex.getWebApiRoutes(method);
    PhpClass phpClass = method.getContainingClass();
    if (phpClass == null) {
        return routesForMethod;
    }
    for (PhpClass parent : method.getContainingClass().getSupers()) {
        for (Method parentMethod : parent.getMethods()) {
            if (parentMethod.getName().equals(method.getName())) {
                routesForMethod.addAll(extractRoutesForMethod(parentMethod));
            }
        }
    }
    return routesForMethod;
}
 
Example 10
Project: hybris-integration-intellij-idea-plugin   File: BeansUtils.java   Source Code and License 6 votes vote down vote up
public static <T extends DomElement, V> GenericAttributeValue<V> expectDomAttributeValue(
    @NotNull final PsiElement element,
    @NotNull final Class<? extends T> domTagClass,
    @NotNull final Function<T, GenericAttributeValue<V>> domGetter
) {
    final DomManager domManager = DomManager.getDomManager(element.getProject());

    if (!(element instanceof XmlElement)) {
        return null;
    }

    final XmlAttribute xmlAttribute = PsiTreeUtil.getParentOfType(element, XmlAttribute.class, false);
    if (xmlAttribute == null) {
        return null;
    }

    final XmlTag xmlParentTag = PsiTreeUtil.getParentOfType(element, XmlTag.class, false);
    DomElement domParentTag = domManager.getDomElement(xmlParentTag);

    return Optional.ofNullable(domParentTag)
                   .map(o -> ObjectUtils.tryCast(o, domTagClass))
                   .map(domGetter)
                   .filter(val -> val == domManager.getDomElement(xmlAttribute))
                   .orElse(null);
}
 
Example 11
Project: hybris-integration-intellij-idea-plugin   File: PsiXmlUtils.java   Source Code and License 6 votes vote down vote up
/**
 * <tagName attributeName="XmlAttributeValue">
 */
public static XmlAttributeValuePattern tagAttributeValuePattern(
    String attributeName,
    String fileName
) {
    return XmlPatterns
        .xmlAttributeValue()
        .withParent(
            XmlPatterns
                .xmlAttribute(attributeName)
                .withParent(
                    XmlPatterns
                        .xmlTag()
                )
        ).inside(
            XmlPatterns.psiElement(XmlTag.class)
        ).inFile(XmlPatterns.psiFile()
                            .withName(XmlPatterns.string().endsWith(fileName + ".xml")));
}
 
Example 12
Project: hybris-integration-intellij-idea-plugin   File: ValidateContextImpl.java   Source Code and License 6 votes vote down vote up
@Nullable
private static PsiElement findByLineAndColumn(
    @NotNull final PsiElement file,
    @Nullable final Point columnAndLine
) {
    if (columnAndLine == null) {
        return file;
    }
    final int line = columnAndLine.y - 1;
    final int column = columnAndLine.x - 1;

    PsiElement leaf = findByLineAndColumn(file, line, column);

    if (leaf instanceof PsiWhiteSpace) {
        leaf = PsiTreeUtil.prevVisibleLeaf(leaf);
    }

    final PsiElement tag = leaf instanceof XmlTag ? leaf : PsiTreeUtil.getParentOfType(leaf, XmlTag.class);
    return tag == null ? leaf : tag;
}
 
Example 13
Project: Android-Resource-Usage-Count   File: UsageCountLineProvider.java   Source Code and License 6 votes vote down vote up
private int findTagUsage(XmlTag element) {
    final FindUsagesHandler handler = FindUsageUtils.getFindUsagesHandler(element, element.getProject());
    if (handler != null) {
        final FindUsagesOptions findUsagesOptions = handler.getFindUsagesOptions();
        final PsiElement[] primaryElements = handler.getPrimaryElements();
        final PsiElement[] secondaryElements = handler.getSecondaryElements();
        Factory factory = new Factory() {
            public UsageSearcher create() {
                return FindUsageUtils.createUsageSearcher(primaryElements, secondaryElements, handler, findUsagesOptions, (PsiFile) null);
            }
        };
        UsageSearcher usageSearcher = (UsageSearcher)factory.create();
        final AtomicInteger mCount = new AtomicInteger(0);
        usageSearcher.generate(new Processor<Usage>() {
            @Override
            public boolean process(Usage usage) {
                if (ResourceUsageCountUtils.isUsefulUsageToCount(usage)) {
                    mCount.incrementAndGet();
                }
                return true;
            }
        });
        return mCount.get();
    }
    return 0;
}
 
Example 14
Project: Android-Resource-Usage-Count   File: ResourceUsageCountUtils.java   Source Code and License 6 votes vote down vote up
/**
 * valid tag to count
 */
static boolean isTargetTagToCount(PsiElement tag) {
    if (tag == null || !(tag instanceof XmlTag) || TextUtils.isEmpty(((XmlTag)tag).getName())) {
        return false;
    }
    String name = ((XmlTag)tag).getName();
    return name.equals("array")
            || name.equals("attr")
            || name.equals("bool")
            || name.equals("color")
            || name.equals("declare-styleable")
            || name.equals("dimen")
            || name.equals("drawable")
            || name.equals("eat-comment")
            || name.equals("fraction")
            || name.equals("integer")
            || name.equals("integer-array")
            || name.equals("item")
            || name.equals("plurals")
            || name.equals("string")
            || name.equals("string-array")
            || name.equals("style");
}
 
Example 15
Project: Android-Resource-Usage-Count   File: UsageCountLineProvider.java   Source Code and License 6 votes vote down vote up
private int findTagUsage(XmlTag element) {
    final FindUsagesHandler handler = FindUsageUtils.getFindUsagesHandler(element, element.getProject());
    if (handler != null) {
        final FindUsagesOptions findUsagesOptions = handler.getFindUsagesOptions();
        final PsiElement[] primaryElements = handler.getPrimaryElements();
        final PsiElement[] secondaryElements = handler.getSecondaryElements();
        Factory factory = new Factory() {
            public UsageSearcher create() {
                return FindUsageUtils.createUsageSearcher(primaryElements, secondaryElements, handler, findUsagesOptions, (PsiFile) null);
            }
        };
        UsageSearcher usageSearcher = (UsageSearcher)factory.create();
        final AtomicInteger mCount = new AtomicInteger(0);
        usageSearcher.generate(new Processor<Usage>() {
            @Override
            public boolean process(Usage usage) {
                if (ResourceUsageCountUtils.isUsefulUsageToCount(usage)) {
                    mCount.incrementAndGet();
                }
                return true;
            }
        });
        return mCount.get();
    }
    return 0;
}
 
Example 16
Project: Android-Resource-Usage-Count   File: ResourceUsageCountUtils.java   Source Code and License 6 votes vote down vote up
/**
 * valid tag to count
 */
static boolean isTargetTagToCount(PsiElement tag) {
    if (tag == null || !(tag instanceof XmlTag) || TextUtils.isEmpty(((XmlTag)tag).getName())) {
        return false;
    }
    String name = ((XmlTag)tag).getName();
    return name.equals("array")
            || name.equals("attr")
            || name.equals("bool")
            || name.equals("color")
            || name.equals("declare-styleable")
            || name.equals("dimen")
            || name.equals("drawable")
            || name.equals("eat-comment")
            || name.equals("fraction")
            || name.equals("integer")
            || name.equals("integer-array")
            || name.equals("item")
            || name.equals("plurals")
            || name.equals("string")
            || name.equals("string-array")
            || name.equals("style");
}
 
Example 17
Project: intellij-ce-playground   File: TreeIncrementalUpdateTest.java   Source Code and License 6 votes vote down vote up
public void testRemoveAttributeParent() throws Throwable {
  final XmlFile file = (XmlFile)createFile("file.xml", "<?xml version='1.0' encoding='UTF-8'?>\n" +
                                                       "<!DOCTYPE ejb-jar PUBLIC \"-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN\" \"http://java.sun.com/dtd/ejb-jar_2_0.dtd\">\n" +
                                                       "<a>\n" +
                                                       " <child-element xxx=\"239\"/>\n" +
                                                       "</a>");
  final DomFileElementImpl<MyElement> fileElement =
    getDomManager().getFileElement(file, MyElement.class, "a");
  myCallRegistry.clear();
  final MyElement rootElement = fileElement.getRootElement();
  final MyElement oldLeaf = rootElement.getChildElements().get(0);
  final GenericAttributeValue<String> xxx = oldLeaf.getXxx();
  final XmlTag oldLeafTag = oldLeaf.getXmlTag();

  new WriteCommandAction(getProject()) {
    @Override
    protected void run(@NotNull Result result) throws Throwable {
      oldLeafTag.delete();
    }
  }.execute();

  assertFalse(oldLeaf.isValid());
  assertFalse(xxx.isValid());
}
 
Example 18
Project: dimenify   File: AbstractDimenAction.java   Source Code and License 6 votes vote down vote up
protected XmlTag[] getDimenValuesInFile(XmlFile xmlFile) {
    XmlTag[] dimens = null;
    if (xmlFile.getDocument() != null && xmlFile.getDocument().getRootTag() != null) {
        String name = xmlFile.getDocument().getRootTag().getName();

        switch (name) {
            case "xml":
                XmlTag resourcesTag = xmlFile.getDocument().getRootTag().findFirstSubTag("resources");
                if (resourcesTag != null) {
                    dimens = resourcesTag.findSubTags("dimen");
                }
                break;
            case "resources":
                dimens = xmlFile.getDocument().getRootTag().findSubTags("dimen");
                break;

        }
    }
    return dimens;
}
 
Example 19
Project: intellij-ce-playground   File: DomMetaDataContributor.java   Source Code and License 6 votes vote down vote up
@Override
public void contributeMetaData(MetaDataRegistrar registrar) {
  registrar.registerMetaData(new ElementFilter() {
    @Override
    public boolean isAcceptable(Object element, PsiElement context) {
      if (element instanceof XmlTag) {
        final XmlTag tag = (XmlTag)element;
        final DomElement domElement = DomManager.getDomManager(tag.getProject()).getDomElement(tag);
        if (domElement != null) {
          return domElement.getGenericInfo().getNameDomElement(domElement) != null;
        }
      }
      return false;
    }

    @Override
    public boolean isClassAcceptable(Class hintClass) {
      return XmlTag.class.isAssignableFrom(hintClass);
    }
  }, DomMetaData.class);
}
 
Example 20
Project: intellij-ce-playground   File: DomChildrenTest.java   Source Code and License 6 votes vote down vote up
public void testUndefineLastFixedChild() throws Throwable {
  new WriteCommandAction.Simple(getProject()) {
    @Override
    protected void run() throws Throwable {
      final MyElement element =
        createElement("<a>" + "<child>1</child>" + "<child attr=\"\">2</child>" + "<child attr=\"\">2</child>" + "</a>");
      final MyElement child = element.getChild();
      final MyElement child2 = element.getChild2();
      child2.undefine();

      myCallRegistry.putExpected(new DomEvent(child2, false));
      myCallRegistry.assertResultsAndClear();

      XmlTag[] subTags = element.getXmlTag().getSubTags();
      assertTrue(child.isValid());
      assertTrue(child2.isValid());
      assertEquals(1, subTags.length);
      assertNull(child2.getXmlTag());

      assertEquals(element, child.getParent());
      assertEquals(element, child2.getParent());
    }
  }.execute().throwException();
}
 
Example 21
Project: intellij-ce-playground   File: DomAttributeXmlDescriptor.java   Source Code and License 6 votes vote down vote up
static String getQualifiedAttributeName(PsiElement context, XmlName xmlName) {
  final String localName = xmlName.getLocalName();
  if (context instanceof XmlTag) {
    final XmlTag tag = (XmlTag)context;
    final DomInvocationHandler handler = DomManagerImpl.getDomManager(context.getProject()).getDomHandler(tag);
    if (handler != null) {
      final String ns = handler.createEvaluatedXmlName(xmlName).getNamespace(tag, handler.getFile());
      if (!ns.equals(XmlUtil.EMPTY_URI) && !ns.equals(tag.getNamespace())) {
        final String prefix = tag.getPrefixByNamespace(ns);
        if (StringUtil.isNotEmpty(prefix)) {
          return prefix + ":" + localName;
        }
      }
    }
  }

  return localName;
}
 
Example 22
Project: intellij-ce-playground   File: MavenDomUtil.java   Source Code and License 6 votes vote down vote up
@Nullable
public static XmlTag findTag(@NotNull DomElement domElement, @NotNull String path) {
  List<String> elements = StringUtil.split(path, ".");
  if (elements.isEmpty()) return null;

  Pair<String, Integer> nameAndIndex = translateTagName(elements.get(0));
  String name = nameAndIndex.first;
  Integer index = nameAndIndex.second;

  XmlTag result = domElement.getXmlTag();
  if (result == null || !name.equals(result.getName())) return null;
  result = getIndexedTag(result, index);

  for (String each : elements.subList(1, elements.size())) {
    nameAndIndex = translateTagName(each);
    name = nameAndIndex.first;
    index = nameAndIndex.second;

    result = result.findFirstSubTag(name);
    if (result == null) return null;
    result = getIndexedTag(result, index);
  }
  return result;
}
 
Example 23
Project: intellij-ce-playground   File: DomFileDescription.java   Source Code and License 6 votes vote down vote up
/**
 * Consider using {@link DomService#getXmlFileHeader(com.intellij.psi.xml.XmlFile)} when implementing this.
 */
@SuppressWarnings({"MethodMayBeStatic"})
@NotNull
public List<String> getAllowedNamespaces(@NotNull String namespaceKey, @NotNull XmlFile file) {
  final NotNullFunction<XmlTag, List<String>> function = myNamespacePolicies.get(namespaceKey);
  if (function instanceof ConstantFunction) {
    return function.fun(null);
  }

  if (function != null) {
    final XmlDocument document = file.getDocument();
    if (document != null) {
      final XmlTag tag = document.getRootTag();
      if (tag != null) {
        return function.fun(tag);
      }
    }
  } else {
    return Collections.singletonList(namespaceKey);
  }
  return Collections.emptyList();
}
 
Example 24
Project: intellij-ce-playground   File: MavenDomGutterAnnotator.java   Source Code and License 6 votes vote down vote up
@Override
public String getElementText(XmlTag tag) {
  DomElement domElement = DomManager.getDomManager(tag.getProject()).getDomElement(tag);
  if (domElement != null) {
    MavenDomProjectModel model = domElement.getParentOfType(MavenDomProjectModel.class, false);
    if (model != null) {
      MavenProject mavenProject = MavenDomUtil.findProject(model);
      if (mavenProject != null) return mavenProject.getDisplayName();

      String name = model.getName().getStringValue();
      if (!StringUtil.isEmptyOrSpaces(name)) {
        return name;
      }
    }
  }

  return tag.getContainingFile().getName();
}
 
Example 25
Project: intellij-ce-playground   File: XmlTagRuleProviderBase.java   Source Code and License 6 votes vote down vote up
@Override
public void annotate(@NotNull XmlTag tag, @NotNull ProblemsHolder holder) {
  for (String attributeName : myAttributeNames) {
    if (tag.getAttribute(attributeName) != null) {
      return;
    }
  }

  if (!isClosedTag(tag)) return;

  PsiElement tagNameElement = getTagNameElement(tag);
  if (tagNameElement == null) return;

  LocalQuickFix[] fixes = new LocalQuickFix[myAttributeNames.length];
  for (int i = 0; i < myAttributeNames.length; i++) {
    fixes[i] = XmlQuickFixFactory.getInstance().insertRequiredAttributeFix(tag, myAttributeNames[i]);
  }

  holder.registerProblem(tagNameElement, "Tag should have one of following attributes: " + StringUtil.join(myAttributeNames, ", "),
                         myProblemHighlightType,
                         fixes);
}
 
Example 26
Project: intellij-ce-playground   File: Analyser.java   Source Code and License 6 votes vote down vote up
private static Set<String> getIds(@Nullable XmlFile psiFile) {
  final Set<String> result = new HashSet<String>();
  if (psiFile == null) {
    return result;
  }
  psiFile.accept(new XmlRecursiveElementVisitor() {
    @Override
    public void visitXmlTag(XmlTag tag) {
      super.visitXmlTag(tag);
      String id = tag.getAttributeValue("id", SdkConstants.ANDROID_URI);
      if (id != null) {
        result.add(id.substring(getPrefix(id).length()));
      }
    }
  });
  return result;
}
 
Example 27
Project: intellij-ce-playground   File: AndroidPsiUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Get the value of an attribute in the {@link com.intellij.psi.xml.XmlFile} safely (meaning it will acquire the read lock first).
 */
@Nullable
public static String getRootTagAttributeSafely(@NotNull final XmlFile file,
                                               @NotNull final String attribute,
                                               @Nullable final String namespace) {
  Application application = ApplicationManager.getApplication();
  if (!application.isReadAccessAllowed()) {
    return application.runReadAction(new Computable<String>() {
      @Nullable
      @Override
      public String compute() {
        return getRootTagAttributeSafely(file, attribute, namespace);
      }
    });
  } else {
    XmlTag tag = file.getRootTag();
    if (tag != null) {
      XmlAttribute attr = namespace != null ? tag.getAttribute(attribute, namespace) : tag.getAttribute(attribute);
      if (attr != null) {
        return attr.getValue();
      }
    }
    return null;
  }
}
 
Example 28
Project: intellij-ce-playground   File: AndroidFindStyleApplicationsTest.java   Source Code and License 6 votes vote down vote up
public void testGranular1() throws Exception {
  myFixture.copyFileToProject(BASE_PATH + "1_layout.xml", "res/layout/layout.xml");
  final VirtualFile f = myFixture.copyFileToProject(BASE_PATH + "1.xml", "res/values/styles.xml");
  myFixture.configureFromExistingVirtualFile(f);
  XmlTag tag = PsiTreeUtil.getParentOfType(myFixture.getElementAtCaret(), XmlTag.class);
  AndroidFindStyleApplicationsAction.MyStyleData styleData = AndroidFindStyleApplicationsAction.getStyleData(tag);
  assertNotNull(styleData);
  AndroidFindStyleApplicationsProcessor processor =
    AndroidFindStyleApplicationsAction.createFindStyleApplicationsProcessor(tag, styleData, null);
  processor.configureScope(AndroidFindStyleApplicationsProcessor.MyScope.PROJECT, null);
  Collection<PsiFile> files = processor.collectFilesToProcess();
  assertEquals(1, files.size());
  XmlFile layoutFile = (XmlFile)files.iterator().next();
  assertInstanceOf(DomManager.getDomManager(myFixture.getProject()).getDomFileDescription(
    (XmlFile)layoutFile), LayoutDomFileDescription.class);
  final List<UsageInfo> usages = new ArrayList<UsageInfo>();
  processor.collectPossibleStyleApplications(layoutFile, usages);
  assertEquals(2, usages.size());
}
 
Example 29
Project: intellij-ce-playground   File: DeprecatedClassUsageInspection.java   Source Code and License 6 votes vote down vote up
@NotNull
@Override
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder,
                                      boolean isOnTheFly,
                                      @NotNull LocalInspectionToolSession session) {
  return new XmlElementVisitor() {
    @Override
    public void visitXmlTag(XmlTag tag) {
      if (tag.getValue().getTextElements().length > 0) {
        checkReferences(tag, holder);
      }
    }

    @Override
    public void visitXmlAttributeValue(XmlAttributeValue value) {
      checkReferences(value, holder);
    }
  };
}
 
Example 30
Project: intellij-ce-playground   File: XmlResourceDomFileDescription.java   Source Code and License 6 votes vote down vote up
@Override
public boolean isMyFile(@NotNull XmlFile file, @Nullable Module module) {
  if (!super.isMyFile(file, module)) {
    return false;
  }
  final XmlTag rootTag = file.getRootTag();

  if (rootTag == null || rootTag.getNamespace().length() > 0) {
    return false;
  }
  for (XmlAttribute attribute : rootTag.getAttributes()) {
    if (attribute.getName().equals("xmlns")) {
      return false;
    }
  }
  return true;
}
 
Example 31
Project: intellij-ce-playground   File: UnwrapTagFix.java   Source Code and License 6 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
  final PsiElement element = descriptor.getPsiElement();
  if (element != null) {
    final PsiFile containingFile = element.getContainingFile();
    LOG.assertTrue(containingFile != null && JavaFxFileTypeFactory.isFxml(containingFile), containingFile == null ? "no containing file found" : "containing file: " + containingFile.getName());
    final XmlTag xmlTag = PsiTreeUtil.getParentOfType(element, XmlTag.class);
    if (xmlTag != null) {
      final XmlTag parentTag = xmlTag.getParentTag();
      final PsiElement[] children = PsiTreeUtil.getChildrenOfType(xmlTag, XmlTagChild.class);
      if (children != null) {
        if (!FileModificationService.getInstance().preparePsiElementsForWrite(element)) return;
        if (children.length > 0) {
          parentTag.addRange(children[0], children[children.length - 1]);
        }
        xmlTag.delete();
        CodeStyleManager.getInstance(project).reformat(parentTag);
      }
    }
  }
}
 
Example 32
Project: intellij-ce-playground   File: TagNameReference.java   Source Code and License 6 votes vote down vote up
@Override
public PsiElement resolve() {
  final XmlTag tag = getTagElement();
  final XmlElementDescriptor descriptor = tag != null ? tag.getDescriptor():null;

  if (LOG.isDebugEnabled()) {
    LOG.debug("Descriptor for tag " +
              (tag != null ? tag.getName() : "NULL") +
              " is " +
              (descriptor != null ? (descriptor.toString() + ": " + descriptor.getClass().getCanonicalName()) : "NULL"));
  }

  if (descriptor != null){
    return descriptor instanceof AnyXmlElementDescriptor ? tag : descriptor.getDeclaration();
  }
  return null;
}
 
Example 33
Project: intellij-ce-playground   File: XmlNSDescriptorImpl.java   Source Code and License 6 votes vote down vote up
public synchronized XmlElementDescriptor[] getSubstitutes(String localName, String namespace) {
  if (!initSubstitutes()) {
    return XmlElementDescriptor.EMPTY_ARRAY;
  }
  Collection<XmlTag> substitutions = mySubstitutions.get(localName);
  if (substitutions.isEmpty()) return XmlElementDescriptor.EMPTY_ARRAY;
  List<XmlElementDescriptor> result = new SmartList<XmlElementDescriptor>();
  for (XmlTag tag : substitutions) {
    final String substAttr = tag.getAttributeValue("substitutionGroup");
    if (substAttr != null && checkElementNameEquivalence(localName, namespace, substAttr, tag)) {
      result.add(createElementDescriptor(tag));
    }
  }

  return result.toArray(new XmlElementDescriptor[result.size()]);
}
 
Example 34
Project: intellij-ce-playground   File: XmlSchemaTest.java   Source Code and License 6 votes vote down vote up
public void testAttributeDescriptor3() throws Exception {
  XmlNSDescriptor NSDescriptor = createDescriptor(
      "<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
      "<xsd:element name=\"purchaseOrder\" type=\"PurchaseOrderType\"/>" +
      "<xsd:complexType name=\"PurchaseOrderType\">" +
      "   <xsd:attribute name=\"orderDate\" type=\"xsd:date\" fixed=\"1 01 2001\"/>" +
      "</xsd:complexType>" +
      "</xsd:schema>");

  final XmlTag tag = XmlTestUtil.tag("purchaseOrder", getProject());
  XmlElementDescriptor elementDescriptor = NSDescriptor.getElementDescriptor(tag);
  XmlAttributeDescriptor attribute = elementDescriptor.getAttributeDescriptor("orderDate", tag);

  assertTrue(!attribute.isEnumerated());
  assertTrue(attribute.isFixed());
  assertTrue(!attribute.isRequired());
  assertEquals("1 01 2001", attribute.getDefaultValue());
}
 
Example 35
Project: intellij-ce-playground   File: CreateXmlElementIntentionAction.java   Source Code and License 6 votes vote down vote up
@Override
public boolean isAvailable(@NotNull final Project project, final Editor editor, final PsiFile file) {
  if (!myIsAvailableEvaluated) {
    final XmlTag tag = PsiTreeUtil.getParentOfType(myRef.getElement(), XmlTag.class);
    if (tag != null) {
      final XmlNSDescriptorImpl descriptor = myRef.getDescriptor(tag, myRef.getCanonicalText());

      if (descriptor != null &&
          descriptor.getDescriptorFile() != null &&
          descriptor.getDescriptorFile().isWritable()
         ) {
        myTargetFile = descriptor.getDescriptorFile();
      }
    }
    myIsAvailableEvaluated = true;
  }
  return myTargetFile != null;
}
 
Example 36
Project: mule-intellij-plugins   File: MuleSchemaUtils.java   Source Code and License 6 votes vote down vote up
public static void insertSchemaLocationLookup(XmlFile xmlFile, String namespace, String locationLookup) {
    final XmlTag rootTag = xmlFile.getRootTag();
    if (rootTag == null)
        return;
    final XmlAttribute attribute = rootTag.getAttribute("xsi:schemaLocation", HTTP_WWW_W3_ORG_2001_XMLSCHEMA);
    if (attribute != null) {
        final String value = attribute.getValue();
        attribute.setValue(value + "\n\t\t\t" + namespace + " " + locationLookup);
    } else {
        final XmlElementFactory elementFactory = XmlElementFactory.getInstance(xmlFile.getProject());
        final XmlAttribute schemaLocation = elementFactory.createXmlAttribute("xsi:schemaLocation", XmlUtil.XML_SCHEMA_INSTANCE_URI);
        schemaLocation.setValue(namespace + " " + locationLookup);
        rootTag.add(schemaLocation);
    }

}
 
Example 37
Project: intellij-ce-playground   File: ConvertIfToChooseIntention.java   Source Code and License 6 votes vote down vote up
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
    if (!XsltSupport.isXsltFile(file)) return false;

    final int offset = editor.getCaretModel().getOffset();
    final PsiElement element = file.findElementAt(offset);
    if (element == null) return false;
    final XmlTag tag = PsiTreeUtil.getParentOfType(element, XmlTag.class);
    if (tag == null || tag.getParentTag() == null) return false;
    if (!tag.getLocalName().equals("if") || !XsltSupport.isXsltTag(tag)) return false;
    if (tag.getAttributeValue("test") == null) return false;

    final ASTNode node = tag.getNode();
    if (node == null) return false;

    final ASTNode child = XmlChildRole.START_TAG_NAME_FINDER.findChild(node);
    return child != null && child.getTextRange().contains(offset);
}
 
Example 38
Project: intellij-ce-playground   File: RenderedViewHierarchy.java   Source Code and License 6 votes vote down vote up
@Nullable
public List<RenderedView> findViewsByTag(@NotNull XmlTag tag) {
  List<RenderedView> result = null;
  for (RenderedView view : myRoots) {
    List<RenderedView> matches = view.findViewsByTag(tag);
    if (matches != null) {
      if (result != null) {
        result.addAll(matches);
      } else {
        result = matches;
      }
    }
  }

  return result;
}
 
Example 39
Project: intellij-ce-playground   File: AntDomProject.java   Source Code and License 6 votes vote down vote up
@NotNull
public final ClassLoader getClassLoader() {
  ClassLoader loader = myClassLoader;
  if (loader == null) {
    final XmlTag tag = getXmlTag();
    final PsiFile containingFile = tag.getContainingFile();
    final AntBuildFileImpl buildFile = (AntBuildFileImpl)AntConfigurationBase.getInstance(containingFile.getProject()).getAntBuildFile(containingFile);
    if (buildFile != null) {
      loader = buildFile.getClassLoader();
    }
    else {
      AntInstallation antInstallation = getAntInstallation();
      loader = antInstallation.getClassLoader();
    }
    myClassLoader = loader;
  }
  return loader;
}
 
Example 40
Project: intellij-ce-playground   File: XMLExternalAnnotator.java   Source Code and License 6 votes vote down vote up
public static void addMessageWithFixes(final PsiElement context,
                                       final String message,
                                       @NotNull final Validator.ValidationHost.ErrorType type,
                                       AnnotationHolder myHolder,
                                       @NotNull final IntentionAction... fixes) {
  if (message != null && !message.isEmpty()) {
    if (context instanceof XmlTag) {
      addMessagesForTag((XmlTag)context, message, type, myHolder, fixes);
    }
    else {
      if (type == Validator.ValidationHost.ErrorType.ERROR) {
        appendFixes(myHolder.createErrorAnnotation(context, message), fixes);
      }
      else {
        appendFixes(myHolder.createWarningAnnotation(context, message), fixes);
      }
    }
  }
}
 
Example 41
Project: intellij-ce-playground   File: AndroidDomElementDescriptorProvider.java   Source Code and License 6 votes vote down vote up
@Nullable
public static Pair<AndroidDomElement, String> getDomElementAndBaseClassQName(@NotNull XmlTag tag) {
  final PsiFile file = tag.getContainingFile();
  if (!(file instanceof XmlFile)) return null;
  Project project = file.getProject();
  if (project.isDefault()) return null;

  final DomManager domManager = DomManager.getDomManager(project);
  if (domManager.getFileElement((XmlFile)file, AndroidDomElement.class) == null) return null;
  
  final DomElement domElement = domManager.getDomElement(tag);
  if (!(domElement instanceof AndroidDomElement)) {
    return null;
  }

  String className = null;
  if (domElement instanceof LayoutViewElement) {
    className = AndroidUtils.VIEW_CLASS_NAME;
  }
  else if (domElement instanceof XmlResourceElement) {
    className = AndroidXmlResourcesUtil.PREFERENCE_CLASS_NAME;
  }
  return Pair.create((AndroidDomElement)domElement, className);
}
 
Example 42
Project: intellij-ce-playground   File: AddMissingAttributesFix.java   Source Code and License 6 votes vote down vote up
@NotNull
private static String getDefaultWidth(@NotNull XmlTag tag) {
  // Depends on parent and child. For now, just do wrap unless it's a layout
  //String tagName = tag.getName();

  // See Change-Id: I335a3bd8e2d7f7866692898ed73492635a5b61ea
  // For the platform layouts the default value is WRAP_CONTENT (and is
  // defined in the ViewGroup.LayoutParams class). The special cases
  // are accommodated in LayoutParams subclasses in the following cases:
  // Subclass                         width           height
  // FrameLayout.LayoutParams:        MATCH_PARENT,   MATCH_PARENT
  // TableLayout.LayoutParams:        MATCH_PARENT,   WRAP_CONTENT
  // TableRow.LayoutParams:           MATCH_PARENT,   WRAP_CONTENT
  XmlTag parentTag = getParentTag(tag);
  if (parentTag != null) {
    String parent = parentTag.getName();
    if (parent.equals(FRAME_LAYOUT) || parent.equals(TABLE_LAYOUT) || parent.equals(TABLE_ROW)) {
      return VALUE_MATCH_PARENT; // TODO: VALUE_FILL_PARENT?
    }
    // TODO: If custom view, check its parentage!
  }

  return VALUE_WRAP_CONTENT;
}
 
Example 43
Project: intellij-ce-playground   File: RadComponentOperations.java   Source Code and License 6 votes vote down vote up
public static RadViewComponent createComponent(@Nullable XmlTag tag, @NotNull MetaModel metaModel) throws Exception {
  RadViewComponent component = (RadViewComponent)metaModel.getModel().newInstance();
  assert component != null : tag;
  component.setMetaModel(metaModel);
  component.setTag(tag);

  Class<RadLayout> layout = metaModel.getLayout();
  if (layout == null) {
    component.setLayout(RadViewLayout.INSTANCE);
  }
  else {
    component.setLayout(layout.newInstance());
  }

  return component;
}
 
Example 44
Project: AppleScript-IDEA   File: DictionaryPropertyImpl.java   Source Code and License 5 votes vote down vote up
public DictionaryPropertyImpl(@NotNull DictionaryComponent classOrRecord, @NotNull String name,
                              @NotNull String code, @NotNull String typeSpecifier,
                              @Nullable String description, @NotNull XmlTag XmlTagProperty, AccessType accessType) {
  super(classOrRecord, name, code, XmlTagProperty, description);
  this.typeSpecifier = typeSpecifier;
  if (accessType != null) {
    this.accessType = accessType;
  }
  assert (myParent instanceof AppleScriptClass || myParent instanceof DictionaryRecord);
}
 
Example 45
Project: AppleScript-IDEA   File: DictionaryPropertyImpl.java   Source Code and License 5 votes vote down vote up
protected DictionaryPropertyImpl(@NotNull DictionaryComponent classOrRecord, @NotNull String name,
                                 @NotNull String code, @NotNull String typeSpecifier,
                                 @Nullable AccessType accessType, @NotNull XmlTag XmlTagProperty) {
  super(classOrRecord, name, code, XmlTagProperty);
  this.typeSpecifier = typeSpecifier;
  this.accessType = accessType;
  assert (myParent instanceof AppleScriptClass || myParent instanceof DictionaryRecord);
}
 
Example 46
Project: AppleScript-IDEA   File: DictionaryClass.java   Source Code and License 5 votes vote down vote up
public DictionaryClass(@NotNull Suite suite, @NotNull String name, @NotNull String code,
                       List<AppleScriptPropertyDefinition> properties, @NotNull XmlTag xmlTagClass,
                       String description, @Nullable String parentClassName) {
  super(suite, name, code, xmlTagClass, description);
  this.properties = properties;
  this.parentClassName = parentClassName;
  this.elementNames = new ArrayList<>();
  this.respondingCommandNames = new ArrayList<>();
}
 
Example 47
Project: AppleScript-IDEA   File: AbstractDictionaryComponent.java   Source Code and License 5 votes vote down vote up
protected AbstractDictionaryComponent(@NotNull P parent, @NotNull String name, @NotNull String code,
                                      @NotNull XmlTag myXmlTag, @Nullable String description) {
  super(myXmlTag, parent);
  this.code = code;
  this.name = name;
  this.description = description;
}
 
Example 48
Project: AppleScript-IDEA   File: AppleScriptCommandImpl.java   Source Code and License 5 votes vote down vote up
public AppleScriptCommandImpl(@NotNull Suite suite, @NotNull String name, @NotNull String code,
                              @Nullable List<CommandParameter> parameters,
                              @Nullable CommandDirectParameter directParameter, @Nullable CommandResult result,
                              @Nullable String description, @NotNull XmlTag xmlTagCommand) {
  super(suite, name, code, xmlTagCommand, description);
  this.directParameter = directParameter;
  this.result = result;
  if (parameters != null) {
    setParameters(parameters);
  }
}
 
Example 49
Project: AppleScript-IDEA   File: CommandParameterImpl.java   Source Code and License 5 votes vote down vote up
public CommandParameterImpl(@NotNull AppleScriptCommand myCommand, @NotNull String name, @NotNull String code,
                            boolean optional, @NotNull String typeSpecifier,
                            @Nullable String description, @NotNull XmlTag xmlTagParameter) {
  super(myCommand, name, code, xmlTagParameter, description);
  this.typeSpecifier = typeSpecifier;
  this.optional = optional;
}
 
Example 50
Project: idea-php-typo3-plugin   File: TranslationUtilTest.java   Source Code and License 5 votes vote down vote up
public void testCanFindDefinitionElements() {
    assertSize(2, TranslationUtil.findDefinitionElements(myFixture.getProject(), "LLL:EXT:foo/sample.xlf:sys_language.language_isocode.ab"));
    assertSize(1, TranslationUtil.findDefinitionElements(myFixture.getProject(), "LLL:EXT:foo/de.sample.xlf:sys_language.language_isocode.ab"));

    PsiElement[] definitionElements = TranslationUtil.findDefinitionElements(myFixture.getProject(), "LLL:EXT:foo/sample.xlf:sys_language.language_isocode.ab");
    for (PsiElement definitionElement : definitionElements) {
        assertInstanceOf(definitionElement, XmlTag.class);

        XmlTag tag = (XmlTag) definitionElement;
        assertEquals("In case the element is XLIFF, the tag name is trans-unit", "trans-unit", tag.getName());
    }
}
 
Example 51
Project: magento2-phpstorm-plugin   File: LayoutIndex.java   Source Code and License 5 votes vote down vote up
private static void collectComponentDeclarations(XmlTag parentTag, List<XmlTag> results, String componentName, String componentType, ComponentMatcher componentMatcher) {
    for (XmlTag childTag: parentTag.getSubTags()) {
        if (componentType.equals(childTag.getName()) && componentMatcher.matches(componentName, childTag)) {
            results.add(childTag);
        } else if(childTag.getSubTags().length > 0 ) {
            collectComponentDeclarations(childTag, results, componentName, componentType, componentMatcher);
        }
    }
}
 
Example 52
Project: magento2-phpstorm-plugin   File: LayoutIndex.java   Source Code and License 5 votes vote down vote up
public static List<XmlTag> getBlockClassDeclarations(PhpClass phpClass, Project project) {
    String className = phpClass.getPresentableFQN();

    List<XmlTag> blockTags = getComponentDeclarations(className, "block", BlockClassNameIndex.KEY, project, new ClassComponentMatcher());
    List<XmlTag> decoratedBlockTags = new ArrayList<>();
    for (XmlTag blockTag: blockTags) {
        decoratedBlockTags.add(new LayoutBlockLineMarkerXmlTagDecorator(blockTag));
    }
    return decoratedBlockTags;
}
 
Example 53
Project: magento2-phpstorm-plugin   File: VirtualTypeIndex.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public DataIndexer<String, String, FileContent> getIndexer() {
    return inputData -> {
        Map<String, String> map = new THashMap<>();
        PsiFile psiFile = inputData.getPsiFile();
        if (!Settings.isEnabled(psiFile.getProject())) {
            return map;
        }

        if (psiFile instanceof XmlFile) {
            XmlDocument xmlDocument = ((XmlFile) psiFile).getDocument();
            if (xmlDocument != null) {
                XmlTag xmlRootTag = xmlDocument.getRootTag();
                if (xmlRootTag != null) {
                    for (XmlTag virtualTypeTag : xmlRootTag.findSubTags("virtualType")) {
                        String name = virtualTypeTag.getAttributeValue("name");
                        String type = virtualTypeTag.getAttributeValue("type");

                        if (name != null && type != null && !name.isEmpty() && !type.isEmpty()) {
                            map.put(name, type);
                        }
                    }
                }
            }
        }
        return map;
    };
}
 
Example 54
Project: magento2-phpstorm-plugin   File: TypeConfigurationIndex.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public String getDescription() {
    XmlTag typeTag = xmlTag.getParentTag();
    if (typeTag == null) {
        return xmlTag.getName();
    }
    String type = typeTag.getAttributeValue(NAME_ATTRIBUTE);
    if (type == null) {
        return xmlTag.getName();
    }

    return String.format("plugin for %s", type);
}
 
Example 55
Project: magento2-phpstorm-plugin   File: LayoutDataIndexer.java   Source Code and License 5 votes vote down vote up
private void fillResultMap(XmlTag parentTag, Map<String, Void> resultMap) {
    for (XmlTag childTag: parentTag.getSubTags()) {
        if (childTag.getName().equals(indexTag)) {
            String attributeValue = childTag.getAttributeValue(indexAttribute);
            if (attributeValue != null) {
                attributeValue = valueProcessor != null ? valueProcessor.apply(attributeValue) : attributeValue;
                resultMap.put(attributeValue, null);
            }
        }
        fillResultMap(childTag, resultMap);
    }
}
 
Example 56
Project: magento2-phpstorm-plugin   File: WebApiTypeIndex.java   Source Code and License 5 votes vote down vote up
@NotNull
@Override
public DataIndexer<String, Void, FileContent> getIndexer() {
    return inputData -> {
        Map<String, Void> map = new HashMap<>();

        PsiFile psiFile = inputData.getPsiFile();
        if (!Settings.isEnabled(psiFile.getProject())) {
            return map;
        }

        if (!(psiFile instanceof XmlFile)) {
            return map;
        }

        XmlDocument document = ((XmlFile) psiFile).getDocument();
        if (document == null) {
            return map;
        }

        XmlTag xmlTags[] = PsiTreeUtil.getChildrenOfType(psiFile.getFirstChild(), XmlTag.class);
        if (xmlTags == null) {
            return map;
        }

        for (XmlTag xmlTag : xmlTags) {
            if (xmlTag.getName().equals("routes")) {
                for (XmlTag routeNode : xmlTag.findSubTags("route")) {
                    for (XmlTag serviceNode : routeNode.findSubTags("service")) {
                        String typeName = serviceNode.getAttributeValue("class");
                        if (typeName != null) {
                            map.put(PhpLangUtil.toPresentableFQN(typeName), null);
                        }
                    }
                }
            }
        }
        return map;
    };
}
 
Example 57
Project: magento2-phpstorm-plugin   File: WebApiTypeIndex.java   Source Code and License 5 votes vote down vote up
/**
 * Find routes related to the specified method within single webapi.xml
 */
private static void fillRelatedTags(String classFqn, String methodFqn, XmlTag parentTag, List<XmlTag> tagsReferences) {
    for (XmlTag routeNode : parentTag.findSubTags("route")) {
        for (XmlTag serviceNode : routeNode.findSubTags("service")) {
            String typeName = serviceNode.getAttributeValue("class");
            String methodName = serviceNode.getAttributeValue("method");
            if (typeName != null && typeName.equals(classFqn)
                && methodName != null && methodName.equals(methodFqn)
            ) {
                tagsReferences.add(new WebApiLineMarkerXmlTagDecorator(routeNode));
            }
        }
    }
}
 
Example 58
Project: magento2-phpstorm-plugin   File: EventNameIndex.java   Source Code and License 5 votes vote down vote up
private void grabEventNamesFromXmlFile(XmlFile file, Map<String, Void> map) {
    XmlDocument xmlDocument = file.getDocument();
    if (xmlDocument != null) {
        XmlTag xmlRootTag = xmlDocument.getRootTag();
        if (xmlRootTag != null) {
            for (XmlTag eventTag : xmlRootTag.findSubTags("event")) {
                String name = eventTag.getAttributeValue("name");
                if (name != null && !name.isEmpty()) {
                    map.put(name, null);
                }
            }
        }
    }
}
 
Example 59
Project: magento2-phpstorm-plugin   File: ClassConfigurationLineMarkerProvider.java   Source Code and License 5 votes vote down vote up
@Override
public void collectSlowLineMarkers(@NotNull List<PsiElement> list, @NotNull Collection<LineMarkerInfo> collection) {
    if (list.size() > 0) {
        if (!Settings.isEnabled(list.get(0).getProject())) {
            return;
        }
    }
    for (PsiElement psiElement: list) {
        if (psiElement instanceof PhpClass) {
            List<XmlTag> results = new ArrayList<XmlTag>();
            results.addAll(TypeConfigurationIndex.getClassConfigurations((PhpClass) psiElement));
            results.addAll(LayoutIndex.getBlockClassDeclarations((PhpClass) psiElement, psiElement.getProject()));

            if (!(results.size() > 0)) {
                continue;
            }
            results.sort(Comparator.comparing(XmlTag::getName));

            StringBuilder tooltipText = new StringBuilder("Navigate to configuration:");
            for (XmlTag resultItem: results) {
                tooltipText.append("\n  ").append(resultItem.getName());
            }
            NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder
                    .create(AllIcons.FileTypes.Xml)
                    .setTargets(results)
                    .setTooltipText(tooltipText.toString());

            collection.add(builder.createLineMarkerInfo(psiElement));
        }
    }
}
 
Example 60
Project: magento2-phpstorm-plugin   File: WebApiLineMarkerProvider.java   Source Code and License 5 votes vote down vote up
@Override
public void collectSlowLineMarkers(@NotNull List<PsiElement> psiElements, @NotNull Collection<LineMarkerInfo> collection) {
    if (psiElements.size() > 0) {
        if (!Settings.isEnabled(psiElements.get(0).getProject())) {
            return;
        }
    }
    for (PsiElement psiElement: psiElements) {
        WebApiRoutesCollector collector = new WebApiRoutesCollector();
        List<XmlTag> results = new ArrayList<>();
        if (psiElement instanceof Method) {
            results = collector.getRoutes((Method) psiElement);
        } else if (psiElement instanceof PhpClass) {
            results = collector.getRoutes((PhpClass) psiElement);
        }

        if (!(results.size() > 0)) {
            continue;
        }

        StringBuilder tooltipText = new StringBuilder("Navigate to Web API configuration:<pre>");
        for (XmlTag routeTag : results) {
            tooltipText.append(routeTag.getName()).append("\n");
        }
        tooltipText.append("</pre>");
        NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder
                .create(MagentoIcons.WEB_API)
                .setTargets(results)
                .setTooltipText(tooltipText.toString());
        collection.add(builder.createLineMarkerInfo(psiElement));
    }
}