PHPstorm plugin create statement
How I can create a php statement from text and write it to method body from AnAction class?
I want to crate statement like:
$qb->addSelect('a');
I saw in other plugin usage of class `com.jetbrains.php.lang.psi.PhpPsiElementFactory` but this file is included in my php-openapi.jar.
请先登录再写评论。
PhpPsiElementFactory is located in php.jar. While it's an internal class and subject to change, you can still use it.
final String text = "$qb->addSelect('a');";final Statement statement = PhpPsiElementFactory.createStatement(getProject(), text);
final PsiElement groupStatement = method.getLastChild();
if (groupStatement instanceof GroupStatement) {
final PsiElement closingBrace = groupStatement.getLastChild();
if (PhpPsiUtil.isOfType(closingBrace, PhpTokenTypes.chRBRACE)) {
groupStatement.addBefore(statement, closingBrace);
}
}
Alternatively, you can use PsiFileFactory, which is a part of the IntelliJ platform API, directly.
final String text = "$qb->addSelect('a');";final PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(getProject());
final PsiFile file = psiFileFactory.createFileFromText("temp.php", PhpFileType.INSTANCE, "<?php\n" + text);
final PsiElement groupStatement = file.getFirstChild();
if (groupStatement instanceof GroupStatement) {
final PsiElement statement = groupStatement.getLastChild();
if (statement instanceof Statement) {
// TODO here's your code
}
}
"this file is included in my php-openapi.jar"
I guess you mean its NOT included...
com.jetbrains.php.lang.psi.PhpPsiElementFactory#createStatement is indeed the most safe way to create a statement from text.
Unfortunately some of important classes are not yet moved to php-openapi.jar.
As to this one - you can use it quite safely, its not likely to disappear/move/break too often.