使用php parser,PHP Parser 简介和应用 - 为你的代码自动补全单元测试

本文介绍了PHP Parser库,用于解析和生成PHP代码的抽象语法树。通过示例展示了如何利用该库为Service层的静态方法自动生成单元测试,实现代码的增量添加测试,提升开发效率。
摘要由CSDN通过智能技术生成

简介

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

用于将抽象语法树转化成代码。

4ae9b628c37e13822ece6e873ca90fb3.png

命名空间

PhpParser\Node

包含抽象语法树的所有节点,代码中的变量声明、类引用、逻辑表达式都可以用对应的Node表示。

PhpParser\Node\Stmt

包含表达式节点,如表示namespace的Namespace、class的Class、类方法的ClassMethod等。在后面示例中我会演示如何解析和修改表达式。

PhpParser\Builder

该命名空间下包含生成节点的工厂类,通过getNode方法可以获得对应的节点。

应用示例

一、解析和生成源代码

二、为代码自动添加测试

需求描述

假设我们在Service层使用了一系列公共静态方法(public static function)提供服务,我们希望确保每

这是一个早期的 PHP 解析器,相当于实现了 PHPPHP 脚本的解析。示例代码:<?php // Autoload required classes require "vendor/autoload.php"; // Instantiate new parser instance $parser = new PhpParser\Parser(); // Return and print an AST from string contents $astNode = $parser->parseSourceFile('<?php /* comment */ echo "hi!"'); var_dump($astNode); // Gets and prints errors from AST Node. The parser handles errors gracefully, // so it can be used in IDE usage scenarios (where code is often incomplete). $errors = PhpParser\Utilities::getDiagnostics($astNode); var_dump(iterator_to_array($errors)); // Traverse all Node descendants of $astNode foreach ($astNode->getDescendantNodes() as $descendant) {     if ($descendant instanceof \PhpParser\Node\StringLiteral) {         // Print the Node text (without whitespace or comments)         var_dump($descendant->getText());         // All Nodes link back to their parents, so it's easy to navigate the tree.         $grandParent = $descendant->getParent()->getParent();         var_dump($grandParent->getNodeKindName());         // The AST is fully-representative, and round-trippable to the original source.         // This enables consumers to build reliable formatting and refactoring tools.         var_dump($grandParent->getLeadingCommentAndWhitespaceText());     }     // In addition to retrieving all children or descendants of a Node,     // Nodes expose properties specific to the Node type.     if ($descendant instanceof \PhpParser\Node\Expression\EchoExpression) {         $echoKeywordStartPosition = $descendant->echoKeyword->getStartPosition();         // To cut down on memory consumption, positions are represented as a single integer          // index into the document, but their line and character positions are easily retrieved.         $lineCharacterPosition = \PhpParser\Utilities::getLineCharacterPositionFromPosition(             $echoKeywordStartPosition         );         echo "line: $lineCharacterPosition->line, character: $lineCharacterPosition->character";     } } 标签:Tolerant
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值