org.jetbrains.yaml.psi.YAMLKeyValue Java Examples

The following examples show how to use org.jetbrains.yaml.psi.YAMLKeyValue. 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: ServiceLineMarkerProviderTest.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
public void testYamlServiceLineMarker() {
    myFixture.configureByText(YAMLFileType.YML,
        "services:\n" +
            "  foo:\n" +
            "    class: Service\\YamlBar"
    );

    assertLineMarker(PhpPsiElementFactory.createPsiFileFromText(getProject(), "<?php\n" +
        "namespace Service{\n" +
        "    class YamlBar{}\n" +
        "}"
    ), new LineMarker.TargetAcceptsPattern("Navigate to definition", PlatformPatterns.psiElement(YAMLKeyValue.class).with(new PatternCondition<YAMLKeyValue>("KeyText") {
        @Override
        public boolean accepts(@NotNull YAMLKeyValue yamlKeyValue, ProcessingContext processingContext) {
            return yamlKeyValue.getKeyText().equals("foo");
        }
    })));
}
 
Example #2
Source File: ParentKeysPatternCondition.java    From intellij-neos with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean accepts(@NotNull PsiElement psiElement, ProcessingContext processingContext) {
    PsiElement currentElement = psiElement.getParent();
    String expectedKey;
    int i = 0;
    int j = 0;

    while (currentElement != null) {
        if (i < Array.getLength(this.keys)) {
            if (YAMLKeyValue.class.isInstance(currentElement)) {
                expectedKey = this.keys[i++];
                if (!expectedKey.equals("*") && !expectedKey.equals(((YAMLKeyValue) currentElement).getKeyText())) {
                    return false;
                }
            }
        } else if (!this.rootTypes[j++].isInstance(currentElement)) {
            return false;
        }

        currentElement = currentElement.getParent();
    }

    return !(i < Array.getLength(this.keys) || j < Array.getLength(this.rootTypes));
}
 
Example #3
Source File: ControllerMethodInspection.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Nullable
@Override
public String getRouteName() {

    YAMLKeyValue defaultKeyValue = PsiTreeUtil.getParentOfType(this.psiElement.getParent(), YAMLKeyValue.class);
    if(defaultKeyValue == null) {
        return null;
    }

    YAMLKeyValue def = PsiTreeUtil.getParentOfType(defaultKeyValue, YAMLKeyValue.class);
    if(def == null) {
        return null;
    }

    return YamlHelper.getYamlKeyName(def);
}
 
Example #4
Source File: NodeTypeReferenceContributor.java    From intellij-neos with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
    YAMLKeyValue yamlElement = (YAMLKeyValue) element;

    // we support the following cases:
    // - superTypes
    // - constraints.nodeTypes
    // - root level (to find other definitions on root)
    if (parentKeyIs(yamlElement, "superTypes")
            || (parentKeyIs(yamlElement, "nodeTypes") && grandparentKeyIs(yamlElement, "constraints"))
            || isOnRootLevel(yamlElement)) {
        return new PsiReference[]{
                new NodeTypeReference(yamlElement)
        };
    }

    return PsiReference.EMPTY_ARRAY;
}
 
Example #5
Source File: YamlCompletionContributor.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private static void addYamlClassMethods(@Nullable PsiElement psiElement, CompletionResultSet completionResultSet, String classTag) {

        if(psiElement == null) {
            return;
        }

        YAMLKeyValue classKeyValue = PsiElementUtils.getChildrenOfType(psiElement, PlatformPatterns.psiElement(YAMLKeyValue.class).withName(classTag));
        if(classKeyValue == null) {
            return;
        }

        PhpClass phpClass = ServiceUtil.getResolvedClassDefinition(psiElement.getProject(), classKeyValue.getValueText());
        if(phpClass != null) {
            PhpElementsUtil.addClassPublicMethodCompletion(completionResultSet, phpClass);
        }
    }
 
Example #6
Source File: EelHelperUtil.java    From intellij-neos with GNU General Public License v3.0 6 votes vote down vote up
public static HashMap<String, String> getHelpersInFile(@NotNull PsiFile psiFile) {
    YAMLKeyValue defaultContext = YAMLUtil.getQualifiedKeyInFile((YAMLFile) psiFile, "Neos", "Fusion", "defaultContext");

    if (defaultContext == null) {
        defaultContext = YAMLUtil.getQualifiedKeyInFile((YAMLFile) psiFile, "TYPO3", "TypoScript", "defaultContext");
    }

    HashMap<String, String> result = new HashMap<>();
    if (defaultContext != null) {
        PsiElement mapping = defaultContext.getLastChild();
        if (mapping instanceof YAMLMapping) {
            for (PsiElement mappingElement : mapping.getChildren()) {
                if (mappingElement instanceof YAMLKeyValue) {
                    YAMLKeyValue keyValue = (YAMLKeyValue) mappingElement;
                    result.put(keyValue.getKeyText(), keyValue.getValueText());
                    NeosProjectService.getLogger().debug(keyValue.getKeyText() + ": " + keyValue.getValueText());
                }
            }
        }
    }

    return result;
}
 
Example #7
Source File: ServiceLineMarkerProviderTest.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
public void testYamlServiceLineMarkerForClassName() {
    myFixture.configureByText(YAMLFileType.YML,
        "services:\n" +
            "  Service\\YamlBar: ~\n"
    );

    assertLineMarker(PhpPsiElementFactory.createPsiFileFromText(getProject(), "<?php\n" +
        "namespace Service{\n" +
        "    class YamlBar{}\n" +
        "}"
    ), new LineMarker.TargetAcceptsPattern("Navigate to definition", PlatformPatterns.psiElement(YAMLKeyValue.class).with(new PatternCondition<YAMLKeyValue>("KeyText") {
        @Override
        public boolean accepts(@NotNull YAMLKeyValue yamlKeyValue, ProcessingContext processingContext) {
            return yamlKeyValue.getKeyText().equals("Service\\YamlBar");
        }
    })));
}
 
Example #8
Source File: ContainerSettingDeprecatedInspection.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
public PsiElementVisitor buildVisitor(final @NotNull ProblemsHolder holder, boolean isOnTheFly) {
    if (!Symfony2ProjectComponent.isEnabled(holder.getProject())) {
        return super.buildVisitor(holder, isOnTheFly);
    }

    return new PsiElementVisitor() {
        @Override
        public void visitElement(PsiElement element) {
            if(element instanceof XmlAttribute) {
                registerXmlAttributeProblem(holder, (XmlAttribute) element);
            } else if(element instanceof YAMLKeyValue) {
                registerYmlRoutePatternProblem(holder, (YAMLKeyValue) element);
            }

            super.visitElement(element);
        }
    };
}
 
Example #9
Source File: SpecIndexer.java    From intellij-swagger with MIT License 6 votes vote down vote up
private Set<String> getReferencedFilesYaml(final PsiFile file, final VirtualFile specDirectory) {
  final Set<String> result = new HashSet<>();

  file.accept(
      new YamlRecursivePsiElementVisitor() {
        @Override
        public void visitKeyValue(@NotNull YAMLKeyValue yamlKeyValue) {
          if (ApiConstants.REF_KEY.equals(yamlKeyValue.getKeyText())
              && yamlKeyValue.getValue() != null) {
            final String refValue = StringUtils.removeAllQuotes(yamlKeyValue.getValueText());

            if (SwaggerFilesUtils.isFileReference(refValue)) {
              getReferencedFileIndexValue(yamlKeyValue.getValue(), refValue, specDirectory)
                  .ifPresent(result::add);
            }
          }
          super.visitKeyValue(yamlKeyValue);
        }
      });

  return result;
}
 
Example #10
Source File: ServiceTagFactory.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Nullable
private static Collection<ServiceTagInterface> create(@NotNull YAMLKeyValue yamlHash) {

    final Collection<ServiceTagInterface> tags = new ArrayList<>();

    YamlHelper.visitTagsOnServiceDefinition(yamlHash, args -> {
        String methodName = args.getAttribute("method");
        if (StringUtils.isBlank(methodName)) {
            return;
        }

        tags.add(args);
    });

    return tags;
}
 
Example #11
Source File: YamlHelperLightTest.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * @see fr.adrienbrault.idea.symfony2plugin.util.yaml.YamlHelper#collectServiceTags
 */
public void testCollectServiceTagsForSymfony33TagsShortcut() {

    YAMLKeyValue fromText = YamlPsiElementFactory.createFromText(getProject(), YAMLKeyValue.class, "" +
        "foo:\n" +
        "  tags:\n" +
        "    - routing.loader_tags_1\n" +
        "    - routing.loader_tags_2\n"
    );

    assertNotNull(fromText);
    Set<String> collection = YamlHelper.collectServiceTags(fromText);

    assertContainsElements(collection, "routing.loader_tags_1");
    assertContainsElements(collection, "routing.loader_tags_2");
}
 
Example #12
Source File: DoctrineYamlMappingDriver.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Nullable
public DoctrineMetadataModel getMetadata(@NotNull DoctrineMappingDriverArguments args) {

    PsiFile psiFile = args.getPsiFile();
    if(!(psiFile instanceof YAMLFile)) {
        return null;
    }

    Collection<DoctrineModelField> fields = new ArrayList<>();
    DoctrineMetadataModel model = new DoctrineMetadataModel(fields);

    for (YAMLKeyValue yamlKeyValue : YamlHelper.getTopLevelKeyValues((YAMLFile) psiFile)) {
        // first line is class name; check of we are right
        if(args.isEqualClass(YamlHelper.getYamlKeyName(yamlKeyValue))) {
            model.setTable(YamlHelper.getYamlKeyValueAsString(yamlKeyValue, "table"));
            fields.addAll(EntityHelper.getModelFieldsSet(yamlKeyValue));
        }
    }

    if(model.isEmpty()) {
        return null;
    }

    return model;
}
 
Example #13
Source File: YamlPermissionGotoCompletionTest.java    From idea-php-drupal-symfony2-bridge with MIT License 6 votes vote down vote up
public void testThatRoutePermissionCompletesAndNavigates() {
    assertCompletionContains(YAMLFileType.YML, "" +
            "config.import_full:\n" +
            "  requirements:\n" +
            "    _permission: '<caret>'",
        "synchronize configuration"
    );

    assertNavigationMatch(YAMLFileType.YML, "" +
            "config.import_full:\n" +
            "  requirements:\n" +
            "    _permission: 'synchronize<caret> configuration'",
        PlatformPatterns.psiElement(YAMLKeyValue.class).with(new PatternCondition<YAMLKeyValue>("key") {
            @Override
            public boolean accepts(@NotNull YAMLKeyValue yamlKeyValue, ProcessingContext processingContext) {
                return "synchronize configuration".equals(yamlKeyValue.getKeyText());
            }
        })
    );
}
 
Example #14
Source File: YamlHelperLightTest.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * @see fr.adrienbrault.idea.symfony2plugin.util.yaml.YamlHelper#visitTagsOnServiceDefinition
 */
public void testVisitTagsOnServiceDefinition() {

    YAMLKeyValue yamlKeyValue = YamlPsiElementFactory.createFromText(getProject(), YAMLKeyValue.class, "foo:\n" +
        "    tags:\n" +
        "       - { name: kernel.event_listener, event: eventName, method: methodName }\n" +
        "       - { name: kernel.event_listener2, event: eventName2, method: methodName2 }\n"
    );

    ListYamlTagVisitor visitor = new ListYamlTagVisitor();
    YamlHelper.visitTagsOnServiceDefinition(yamlKeyValue, visitor);

    assertEquals("kernel.event_listener", visitor.getItem(0).getName());
    assertEquals("eventName", visitor.getItem(0).getAttribute("event"));
    assertEquals("methodName", visitor.getItem(0).getAttribute("method"));

    assertEquals("kernel.event_listener2", visitor.getItem(1).getName());
    assertEquals("eventName2", visitor.getItem(1).getAttribute("event"));
    assertEquals("methodName2", visitor.getItem(1).getAttribute("method"));
}
 
Example #15
Source File: TranslationInsertUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private static PsiElement invokeTranslation(@NotNull final YAMLFile yamlFile, @NotNull final String keyName, @NotNull final String translation) {
    String[] split = keyName.split("\\.");
    PsiElement psiElement = YamlHelper.insertKeyIntoFile(yamlFile, "'" + translation + "'", split);
    if(psiElement == null) {
        return null;
    }

    // resolve target to get value
    YAMLKeyValue target = YAMLUtil.getQualifiedKeyInFile(yamlFile, split);
    if(target != null && target.getValue() != null) {
        return target.getValue();
    } else if(target != null) {
        return target;
    }

    return yamlFile;
}
 
Example #16
Source File: ConfigLineMarkerProvider.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private void visitRootElements(@NotNull Collection<LineMarkerInfo> result, @NotNull PsiElement psiElement, @NotNull LazyConfigTreeSignatures function) {
    PsiElement parent = psiElement.getParent();
    if(!(parent instanceof YAMLKeyValue)) {
        return;
    }

    String keyText = ((YAMLKeyValue) parent).getKeyText();
    Map<String, Collection<String>> treeSignatures = function.value();
    if(!treeSignatures.containsKey(keyText)) {
        return;
    }

    NavigationGutterIconBuilder<PsiElement> builder = NavigationGutterIconBuilder.create(Symfony2Icons.SYMFONY_LINE_MARKER)
        .setTargets(new MyClassIdLazyValue(psiElement.getProject(), treeSignatures.get(keyText), keyText))
        .setTooltipText("Navigate to configuration");

    result.add(builder.createLineMarkerInfo(psiElement));
}
 
Example #17
Source File: MenuIndex.java    From idea-php-drupal-symfony2-bridge with MIT License 6 votes vote down vote up
@NotNull
@Override
public DataIndexer<String, Void, FileContent> getIndexer() {

    return inputData -> {

        Map<String, Void> map = new THashMap<>();

        PsiFile psiFile = inputData.getPsiFile();
        if(!(psiFile instanceof YAMLFile) || !psiFile.getName().endsWith(".menu.yml")) {
            return map;
        }

        for (YAMLKeyValue yamlKeyValue : YamlHelper.getTopLevelKeyValues((YAMLFile) psiFile)) {
            String keyText = yamlKeyValue.getKeyText();
            if(StringUtils.isBlank(keyText)) {
                continue;
            }

            map.put(keyText, null);
        }

        return map;
    };
}
 
Example #18
Source File: FileResourceVisitorUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * foo:
 *   resources: 'FOO'
 */
private static void visitYamlFile(@NotNull YAMLFile yamlFile, @NotNull Consumer<FileResourceConsumer> consumer) {
    for (YAMLKeyValue yamlKeyValue : YamlHelper.getTopLevelKeyValues(yamlFile)) {
        YAMLKeyValue resourceKey = YamlHelper.getYamlKeyValue(yamlKeyValue, "resource", true);
        if(resourceKey == null) {
            continue;
        }

        String resource = PsiElementUtils.trimQuote(resourceKey.getValueText());
        if(StringUtils.isBlank(resource)) {
            continue;
        }

        consumer.consume(new FileResourceConsumer(resourceKey, yamlKeyValue, normalize(resource)));
    }
}
 
Example #19
Source File: FileResourceVisitorUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@NotNull
public AttributeValueInterface getAttributeValue() {
    if(this.attributeValue != null) {
        return this.attributeValue;
    }

    // We use lazy instances
    // @TODO: replace with factory pattern
    if(this.psiElement instanceof YAMLKeyValue) {
        return this.attributeValue = new YamlKeyValueAttributeValue((YAMLKeyValue) this.scope);
    } else if(this.psiElement instanceof XmlTag) {
        return this.attributeValue = new XmlTagAttributeValue((XmlTag) this.scope);
    }

    return this.attributeValue = new DummyAttributeValue(this.psiElement);
}
 
Example #20
Source File: YamlUpdateArgumentServicesCallbackTest.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private void invokeInsert(YAMLFile yamlFile) {
    Collection<YAMLKeyValue> yamlKeyValues = PsiTreeUtil.collectElementsOfType(yamlFile, YAMLKeyValue.class);

    final YamlUpdateArgumentServicesCallback callback = new YamlUpdateArgumentServicesCallback(
        getProject(),
        ContainerUtil.find(yamlKeyValues, new YAMLKeyValueCondition("arguments")),
        ContainerUtil.find(yamlKeyValues, new YAMLKeyValueCondition("foo"))
    );

    CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
        @Override
        public void run() {
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                @Override
                public void run() {
                    callback.insert(Arrays.asList("foo", "bar"));
                }
            });

        }
    }, null, null);
}
 
Example #21
Source File: DuplicateKeyAnnotator.java    From intellij-kubernetes with Apache License 2.0 6 votes vote down vote up
@Override
public void annotate(@NotNull final PsiElement element, @NotNull final AnnotationHolder annotationHolder) {
    if (!KubernetesYamlPsiUtil.isKubernetesFile(element)) {
        return;
    }
    if (element instanceof YAMLMapping) {
        final YAMLMapping mapping = (YAMLMapping) element;
        final Collection<YAMLKeyValue> keyValues = mapping.getKeyValues();
        final Set<String> existingKeys = new HashSet<>(keyValues.size());
        for (final YAMLKeyValue keyValue : keyValues) {
            if (keyValue.getKey() != null && !existingKeys.add(keyValue.getKeyText().trim())) {
                annotationHolder.createErrorAnnotation(keyValue.getKey(), "Duplicated property '" + keyValue.getKeyText() + "'").registerFix(new DeletePropertyIntentionAction());
            }
        }
    }
}
 
Example #22
Source File: YamlCompletionContributor.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, ProcessingContext processingContext, @NotNull CompletionResultSet completionResultSet) {
    YAMLKeyValue yamlKeyValue = PsiTreeUtil.getParentOfType(completionParameters.getOriginalPosition(), YAMLKeyValue.class);
    if(yamlKeyValue != null) {
        PsiElement compoundValue = yamlKeyValue.getParent();
        if(compoundValue instanceof YAMLCompoundValue) {

            // path and pattern are valid
            String pattern = YamlHelper.getYamlKeyValueAsString((YAMLCompoundValue) compoundValue, "path", false);
            if(pattern == null) {
                pattern = YamlHelper.getYamlKeyValueAsString((YAMLCompoundValue) compoundValue, "pattern", false);
            }

            if(pattern != null) {
                Matcher matcher = Pattern.compile("\\{(\\w+)}").matcher(pattern);
                while(matcher.find()){
                    completionResultSet.addElement(LookupElementBuilder.create(matcher.group(1)));
                }
            }

        }
    }
}
 
Example #23
Source File: PropertyNotInModelAnnotator.java    From intellij-kubernetes with Apache License 2.0 6 votes vote down vote up
@Override
public void annotate(@NotNull final PsiElement element, @NotNull final AnnotationHolder annotationHolder) {
    if (!KubernetesYamlPsiUtil.isKubernetesFile(element)) {
        return;
    }
    final ModelProvider modelProvider = ModelProvider.INSTANCE;
    final ResourceTypeKey resourceKey = KubernetesYamlPsiUtil.findResourceKey(element);
    if (resourceKey != null && element instanceof YAMLKeyValue) {
        final YAMLKeyValue keyValue = (YAMLKeyValue) element;
        final Model model = KubernetesYamlPsiUtil.modelForKey(modelProvider, resourceKey, keyValue);
        if (keyValue.getValue() instanceof YAMLMapping && model != null) {
            final YAMLMapping mapping = (YAMLMapping) keyValue.getValue();
            final Set<String> expectedProperties = model.getProperties().keySet();
            //noinspection ConstantConditions
            mapping.getKeyValues()
                   .stream()
                   .filter(k -> !expectedProperties.contains(k.getKeyText().trim()))
                   .forEach(k -> annotationHolder.createWarningAnnotation(k.getKey(), "Property '" + k.getKeyText() + "' is not expected here.").registerFix(new DeletePropertyIntentionAction()));
        }
    }
}
 
Example #24
Source File: YamlDuplicateServiceKeyInspection.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
protected void visitRoot(PsiFile psiFile, String rootName, @NotNull ProblemsHolder holder) {
    if(!(psiFile instanceof YAMLFile)) {
        return;
    }

    YAMLKeyValue yamlKeyValue = YAMLUtil.getQualifiedKeyInFile((YAMLFile) psiFile, rootName);
    if(yamlKeyValue == null) {
        return;
    }

    YAMLCompoundValue yaml = PsiTreeUtil.findChildOfType(yamlKeyValue, YAMLMapping.class);
    if(yaml != null) {
        YamlHelper.attachDuplicateKeyInspection(yaml, holder);
    }
}
 
Example #25
Source File: YamlCompletionContributor.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Override
public boolean invokeAutoPopup(@NotNull PsiElement position, char typeChar) {
    // Only for Yaml tag places (scalar values)
    //   key: !<caret>
    if (!YamlElementPatternHelper.getSingleLineTextOrTag().accepts(position)
        && !(position.getPrevSibling() instanceof YAMLKeyValue)
        && !(position.getParent() instanceof YAMLSequenceItem)
        && !(position.getParent() instanceof YAMLSequence)
    ) {
        return super.invokeAutoPopup(position, typeChar);
    }

    return typeChar == '!';
}
 
Example #26
Source File: ContainerSettingDeprecatedInspection.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private void registerYmlRoutePatternProblem(@NotNull ProblemsHolder holder, @NotNull YAMLKeyValue element) {
    String s = PsiElementUtils.trimQuote(element.getKeyText());
    if(("factory_class".equals(s) || "factory_method".equals(s) || "factory_service".equals(s)) && YamlElementPatternHelper.getInsideServiceKeyPattern().accepts(element)) {
        // services:
        //   foo:
        //      factory_*:
        registerProblem(holder, element.getKey());
    }
}
 
Example #27
Source File: FormUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * acme_demo.form.type.gender:
 *  class: espend\Form\TypeBundle\Form\FooType
 *  tags:
 *   - { name: form.type, alias: foo_type_alias  }
 *   - { name: foo  }
 */
@NotNull
public static Map<String, Set<String>> getTags(@NotNull YAMLFile yamlFile) {
    Map<String, Set<String>> map = new HashMap<>();

    for(YAMLKeyValue yamlServiceKeyValue : YamlHelper.getQualifiedKeyValuesInFile(yamlFile, "services")) {
        String serviceName = yamlServiceKeyValue.getName();
        Set<String> serviceTagMap = YamlHelper.collectServiceTags(yamlServiceKeyValue);
        if(serviceTagMap.size() > 0) {
            map.put(serviceName, serviceTagMap);
        }
    }

    return map;
}
 
Example #28
Source File: DoctrineMetadataPattern.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
/**
 * fields:
 *  i<caret>d: []
 *
 * embedOne:
 *  add<caret>ress: []
 */
public static PsiElementPattern.Capture<PsiElement> getYamlFieldName() {
    return PlatformPatterns.psiElement(YAMLTokenTypes.SCALAR_KEY)
        .withParent(
            PlatformPatterns.psiElement(YAMLKeyValue.class).withParent(
                PlatformPatterns.psiElement(YAMLCompoundValue.class).withParent(
                    PlatformPatterns.psiElement(YAMLKeyValue.class).withName(PlatformPatterns.string().oneOf(
                        "id", "fields", "embedOne", "embedMany", "referenceOne", "referenceMany", "oneToOne", "oneToMany", "manyToOne", "manyToMany"
                    ))
                )
            )
        );
}
 
Example #29
Source File: KubernetesYamlPsiUtil.java    From intellij-kubernetes with Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether the element is within a Kubernetes YAML file. This is done by checking for the presence of "apiVersion" or "kind" as top-level keys within the first document of the file.
 *
 * @param element an element within the file to check.
 * @return true if the element is within A Kubernetes YAML file, otherwise, false.
 */
public static boolean isKubernetesFile(final PsiElement element) {
    final PsiFile file = element.getContainingFile();
    if (file instanceof YAMLFile) {
        final Collection<YAMLKeyValue> keys = YAMLUtil.getTopLevelKeys((YAMLFile) file);
        return keys.stream().map(YAMLKeyValue::getKeyText).anyMatch(s -> "apiVersion".equals(s) || "kind".equals(s));
    }
    return false;
}
 
Example #30
Source File: YamlClassInspection.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@NotNull
public PsiElementVisitor buildVisitor(final @NotNull ProblemsHolder holder, boolean isOnTheFly) {
    if (!Symfony2ProjectComponent.isEnabled(holder.getProject())) {
        return super.buildVisitor(holder, isOnTheFly);
    }

    return new PsiElementVisitor() {
        @Override
        public void visitElement(PsiElement psiElement) {
            if ((YamlElementPatternHelper.getSingleLineScalarKey("class", "factory_class").accepts(psiElement) || YamlElementPatternHelper.getParameterClassPattern().accepts(psiElement)) && YamlElementPatternHelper.getInsideServiceKeyPattern().accepts(psiElement)) {
                // foobar.foo:
                //   class: Foobar\Foo
                invoke(psiElement, holder);
            } else if (psiElement.getNode().getElementType() == YAMLTokenTypes.SCALAR_KEY && YamlElementPatternHelper.getServiceIdKeyValuePattern().accepts(psiElement.getParent())) {
                // Foobar\Foo: ~
                String text = PsiElementUtils.getText(psiElement);
                if (StringUtils.isNotBlank(text) && YamlHelper.isClassServiceId(text) && text.contains("\\")) {
                    PsiElement yamlKeyValue = psiElement.getParent();
                    if (yamlKeyValue instanceof YAMLKeyValue && YamlHelper.getYamlKeyValue((YAMLKeyValue) yamlKeyValue, "resource") == null && YamlHelper.getYamlKeyValue((YAMLKeyValue) yamlKeyValue, "exclude") == null) {
                        invoke(psiElement, holder);
                    }
                }
            }

            super.visitElement(psiElement);
        }
    };
}