简介
PHP Parser是由 nikic 开发的一款php抽象语法树(AST)解析工具。PHP Parser同时兼顾接口易用,结构简洁,工具链完善等诸多优点。在工程上,普遍使用PHP Paser生成模板代码,或使用其生成的抽象语法树进行静态分析。
抽象语法树 VS 反射
反射
反射可以在程序运行时动态解析类和方法的结构,基于反射获得的结构,程序可以动态地访问类和类的属性方法,也可以用于创建类实例。相对于抽象语法树,反射取得的结构能够更清晰地反映类结构,因而常用于框架实现路由分发等功能。
抽象语法树
抽象语法树是程序语言源代码经过语法分析和词法分析后获得的解析结构。除反射能够获取到的信息外,还包含了注释、方法与函数的逻辑结构,我们可以认为抽象语法树与源代码是等价的。
PHP Parser详解
功能入口
PhpParser\ParserFactory::create(int $kind, Lexer $lexer = null, array $parserOptions = []): PhpParser\Parser
创建解析器,$kind One of ::PREFER_PHP7, ::PREFER_PHP5, ::ONLY_PHP7 or ::ONLY_PHP5
PhpParser\Parser::parse(string $code, ErrorHandler $errorHandler = null): Node\Stmt[]|null
所有解析器都实现了该方法,传入代码并返回抽象语法树。
PrettyPrinter\Standard::prettyPrintFile($ast): string
用于将抽象语法树转化成代码。
命名空间
PhpParser\Node
包含抽象语法树的所有节点,代码中的变量声明、类引用、逻辑表达式都可以用对应的Node表示。
PhpParser\Node\Stmt
包含表达式节点,如表示namespace的Namespace、class的Class、类方法的ClassMethod等。在后面示例中我会演示如何解析和修改表达式。
PhpParser\Builder
该命名空间下包含生成节点的工厂类,通过getNode方法可以获得对应的节点。
应用示例
一、解析和生成源代码
二、为代码自动添加测试
需求描述
假设我们在Service层使用了一系列公共静态方法(public static function)提供服务,我们希望确保每