Search code examples
javapluginsintellij-ideaphpstormintellij-plugin

Check if PsiElement is a string


When adding 'intentions' to PhpStorm (or other JetBrains IDE's), how can I detect whether a PsiElement is a string? I've based my code off the only intention example I could find. I can't seem to find proper documentation. This is as far as I got:

@NonNls public class SomeIntention extends PsiElementBaseIntentionAction implements IntentionAction {

    public boolean isAvailable(@NotNull Project project, Editor editor, @Nullable PsiElement element) {
        if (element == null || !(element instanceof /* String? */) {
            return false;
        }
    }

}

instanceof String obviously doesn't work, but even using PsiViewer I can't figure out how to test whether it's a string.


Solution

  • The following worked to check if our current node is a string (either double quoted or single quoted):

    ASTNode ast_node = element.getNode();
    
    if(ast_node == null) {
        return false;
    }
    
    IElementType element_type = ast_node.getElementType();
    
    if(element_type != PhpTokenTypes.STRING_LITERAL
    && element_type != PhpTokenTypes.STRING_LITERAL_SINGLE_QUOTE) {
        return false;
    }
    
    return true;
    

    In my case, I only wanted 'raw strings', not strings with variables or concatenation. If any variables or concatenation signs exist in a string, PSI sees those as separate siblings. So I could find raw strings by ruling out strings with siblings:

    // Disregards strings with variables, concatenation, etc.
    if (element.getPrevSibling() != null || element.getNextSibling() != null) {
        return false;
    }
    
    return true;