|
8 | 8 | use PhpParser\Node\Stmt\ClassMethod;
|
9 | 9 | use PhpParser\Node\Stmt\Property;
|
10 | 10 | use PhpParser\Node\Stmt\Return_;
|
| 11 | +use PHPStan\PhpDocParser\Ast\PhpDoc\ReturnTagValueNode; |
| 12 | +use PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode; |
11 | 13 | use PHPStan\Type\ObjectType;
|
| 14 | +use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfoFactory; |
| 15 | +use Rector\Comments\NodeDocBlock\DocBlockUpdater; |
12 | 16 | use Rector\Rector\AbstractRector;
|
13 | 17 | use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
|
14 | 18 | use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
|
|
18 | 22 | */
|
19 | 23 | class ModelCastsPropertyToCastsMethodRector extends AbstractRector
|
20 | 24 | {
|
21 |
| - public function __construct(protected BuilderFactory $builderFactory) |
22 |
| - { |
| 25 | + public function __construct( |
| 26 | + protected BuilderFactory $builderFactory, |
| 27 | + protected PhpDocInfoFactory $phpDocInfoFactory, |
| 28 | + protected DocBlockUpdater $docBlockUpdater, |
| 29 | + ) { |
23 | 30 | }
|
24 | 31 |
|
25 | 32 | public function getRuleDefinition(): RuleDefinition
|
@@ -82,15 +89,39 @@ public function refactor(Node $node): ?Class_
|
82 | 89 | $method = $this->builderFactory->method('casts')
|
83 | 90 | ->setReturnType('array')
|
84 | 91 | ->makeProtected();
|
| 92 | + |
| 93 | + if ($stmt->getDocComment() !== null) { |
| 94 | + $method->setDocComment($stmt->getDocComment()); |
| 95 | + } |
| 96 | + |
| 97 | + unset($node->stmts[$index]); |
| 98 | + |
85 | 99 | // convert the property to a return statement
|
86 | 100 | $method->addStmt(new Return_($stmt->props[0]->default));
|
87 |
| - unset($node->stmts[$index]); |
88 |
| - $node->stmts[] = $method->getNode(); |
| 101 | + $methodNode = $method->getNode(); |
| 102 | + $node->stmts[] = $methodNode; |
| 103 | + |
| 104 | + $this->restorePhpDoc($methodNode); |
89 | 105 |
|
90 | 106 | return $node;
|
91 | 107 | }
|
92 | 108 | }
|
93 | 109 |
|
94 | 110 | return null;
|
95 | 111 | }
|
| 112 | + |
| 113 | + private function restorePhpDoc(ClassMethod|Node $methodNode): void |
| 114 | + { |
| 115 | + $phpDocInfo = $this->phpDocInfoFactory->createFromNodeOrEmpty($methodNode); |
| 116 | + |
| 117 | + $varTagValueNode = $phpDocInfo->getVarTagValueNode(); |
| 118 | + |
| 119 | + if (! $varTagValueNode instanceof VarTagValueNode) { |
| 120 | + return; |
| 121 | + } |
| 122 | + |
| 123 | + $phpDocInfo->addTagValueNode(new ReturnTagValueNode($varTagValueNode->type, $varTagValueNode->description)); |
| 124 | + $phpDocInfo->removeByType(VarTagValueNode::class); |
| 125 | + $this->docBlockUpdater->updateRefactoredNodeWithPhpDocInfo($methodNode); |
| 126 | + } |
96 | 127 | }
|
0 commit comments