Skip to content

Commit

Permalink
[TypeDeclaration] Handle comment + single docblock on TypedPropertyFr…
Browse files Browse the repository at this point in the history
…omAssignsRector (#3264)
  • Loading branch information
samsonasik committed Jan 2, 2023
1 parent a94a11a commit 5b76f7b
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 11 deletions.
20 changes: 9 additions & 11 deletions packages/Comments/NodeDocBlock/DocBlockUpdater.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Rector\Comments\NodeDocBlock;

use PhpParser\Comment;
use PhpParser\Comment\Doc;
use PhpParser\Node;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo;
Expand All @@ -29,16 +30,7 @@ public function updateNodeWithPhpDocInfo(Node $node): void

// make sure, that many separated comments are not removed
if ($phpDoc === '') {
if (count($node->getComments()) > 1) {
foreach ($node->getComments() as $comment) {
$phpDoc .= $comment->getText() . PHP_EOL;
}
}

if ($phpDocInfo->getOriginalPhpDocNode()->children !== []) {
// all comments were removed → null
$node->setAttribute(AttributeKey::COMMENTS, null);
}
$this->setCommentsAttribute($node);

return;
}
Expand All @@ -57,13 +49,19 @@ public function updateRefactoredNodeWithPhpDocInfo(Node $node): void

$phpDocNode = $phpDocInfo->getPhpDocNode();
if ($phpDocNode->children === []) {
$node->setAttribute(AttributeKey::COMMENTS, null);
$this->setCommentsAttribute($node);
return;
}

$node->setDocComment(new Doc((string) $phpDocNode));
}

private function setCommentsAttribute(Node $node): void
{
$comments = array_filter($node->getComments(), static fn (Comment $comment): bool => ! $comment instanceof Doc);
$node->setAttribute(AttributeKey::COMMENTS, $comments);
}

private function resolveChangedPhpDocInfo(Node $node): ?PhpDocInfo
{
$phpDocInfo = $node->getAttribute(AttributeKey::PHP_DOC_INFO);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace Rector\Tests\TypeDeclaration\Rector\Property\TypedPropertyFromAssignsRector\Fixture;

final class WithComment
{
// A comment
/**
* @var \DateTime
*/
private $property;

public function __construct()
{
$this->property = new \DateTime();
}
}

?>
-----
<?php

namespace Rector\Tests\TypeDeclaration\Rector\Property\TypedPropertyFromAssignsRector\Fixture;

final class WithComment
{
// A comment
private \DateTime $property;

public function __construct()
{
$this->property = new \DateTime();
}
}

?>

0 comments on commit 5b76f7b

Please sign in to comment.