如何从PhpParser\Node\Stmt\Property获取所属类的类名
解决Rector中获取属性所属类名的问题
问题原因
你之前通过$currentNode->getAttribute('parent')获取父节点返回null,是因为PhpParser不会自动给节点注入parent属性,而Rector的内部节点遍历流程也不依赖这个原生属性,所以直接读取会失败。
正确解决方案
在Rector环境中,推荐使用框架提供的工具类来获取父节点或直接查找所属类节点,以下是两种可行方法:
方法1:使用ParentNodeResolverInterface遍历父节点
通过Rector内置的ParentNodeResolverInterface来逐级向上查找父节点,直到找到Class_节点:
use PhpParser\Node\Stmt\Property; use PhpParser\Node\Stmt\Class_; use Rector\Core\NodeAnalyzer\ParentNodeResolverInterface; use Rector\Core\Rector\AbstractRector; class YourPropertyRector extends AbstractRector { public function __construct( private readonly ParentNodeResolverInterface $parentNodeResolver ) { } private function getClassNameFromPropertyNode(Property $propertyNode): ?string { $currentNode = $propertyNode; while ($currentNode !== null) { if ($currentNode instanceof Class_) { // 直接使用null安全运算符简化判断 return $currentNode->name?->toString(); } $currentNode = $this->parentNodeResolver->findParent($currentNode); } return null; } }
方法2:使用NodeFinder直接查找父类节点
利用NodeFinder的findParentType方法,可以一步找到最近的Class_父节点,代码更简洁:
use PhpParser\Node\Stmt\Property; use PhpParser\Node\Stmt\Class_; use Rector\Core\NodeFinder\NodeFinder; use Rector\Core\Rector\AbstractRector; class YourPropertyRector extends AbstractRector { public function __construct( private readonly NodeFinder $nodeFinder ) { } private function getClassNameFromPropertyNode(Property $propertyNode): ?string { $classNode = $this->nodeFinder->findParentType($propertyNode, Class_::class); return $classNode?->name?->toString(); } }
额外说明
如果你是在纯PhpParser环境(非Rector)中处理节点,需要自己实现NodeVisitor来手动给节点添加parent属性,但在Rector开发中,优先使用上述框架提供的工具类,避免和内部遍历逻辑冲突。
内容的提问来源于stack exchange,提问作者jave.web
相关产品推荐
相关产品推荐

