This project contains an PHP-Parser based on the current php language specification. It supports PHP version 7.
This project is written in Scala and can be used in Java and Scala. Based on FastParse it transforms an valid PHP-String into an abstract syntax tree.
Import the artifacts from the nexus.
<dependency>
<groupId>de.thm.mni.ii</groupId>
<artifactId>phpparser</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
These simple examples present the basic usage of the parser.
import de.thm.mni.ii.phpparser.PHPParser;
import de.thm.mni.ii.phpparser.ast.Basic;
public class Main {
public static void main(String[] args) {
PHPParser.Result res = (PHPParser.Result) PHPParser.parse("<?php $value = 5;");
if (res instanceof PHPParser.Success) {
Basic.Script s = ((PHPParser.Success) res).script();
System.out.println(s);
} else if (res instanceof PHPParser.Failure) {
String msg = ((PHPParser.Failure) res).fullMsg();
System.out.println(msg);
}
}
}
object Main extends App {
import de.thm.mni.ii.phpparser.PHPParser
PHPParser.parse("<?php $value = 5;") match {
case s: PHPParser.Success => println(s.script)
case f: PHPParser.Failure => println(f.fullMsg)
}
}
The top-level PHPParser performs an parse on a whole script. The result is an instance of PHPParser.Success or PHPParser.Failure.
PHPParser.Success only contains the parsed result. PHPParser.Failure contains additional information about the error. If you need further error information, take a look at the failure-member. FastParse provides additional methods to present the origin of the parse-error.
If you want to parse an specific element of the programing language, you can call parse on any parser in the package parser.
.
├── ...
├── src/main/scala/de/thm/mni/ii/phpparser
│ ├── PHPParser.scala # top-level parser
│ ├── ast/ # case classes of abstract syntax tree
│ └── parser/ # specific parsers for all different elements
└── ...
Feel free to send Pull-Requests to improve this parser. If you find any bug, please report it as issue here on github.
This project is tested against several php-projects, but the current version does not contain unit tests. I would really appreciate it if someone can write some proper unit tests.
- Tobias Viehmann - Initial work
This project is licensed under the MIT License - see the LICENSE file for details