-
-
Notifications
You must be signed in to change notification settings - Fork 439
Expand file tree
/
Copy pathCommentsMerger.php
More file actions
70 lines (55 loc) · 1.91 KB
/
CommentsMerger.php
File metadata and controls
70 lines (55 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
declare(strict_types=1);
namespace Rector\BetterPhpDocParser\Comment;
use PhpParser\Node;
use PhpParser\Node\Stmt\InlineHTML;
use PhpParser\Node\Stmt\Nop;
use Rector\BetterPhpDocParser\PhpDocInfo\PhpDocInfo;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\PhpParser\Comparing\NodeComparator;
final readonly class CommentsMerger
{
public function __construct(
private NodeComparator $nodeComparator,
) {
}
public function mirrorComments(Node $newNode, Node $oldNode): void
{
if ($oldNode instanceof InlineHTML) {
return;
}
if ($this->nodeComparator->areSameNode($newNode, $oldNode)) {
return;
}
$oldPhpDocInfo = $oldNode->getAttribute(AttributeKey::PHP_DOC_INFO);
$newPhpDocInfo = $newNode->getAttribute(AttributeKey::PHP_DOC_INFO);
if ($newPhpDocInfo instanceof PhpDocInfo) {
if (! $oldPhpDocInfo instanceof PhpDocInfo) {
return;
}
if ((string) $oldPhpDocInfo->getPhpDocNode() !== (string) $newPhpDocInfo->getPhpDocNode()) {
return;
}
}
$newNode->setAttribute(AttributeKey::PHP_DOC_INFO, $oldPhpDocInfo);
if (! $newNode instanceof Nop) {
$newNode->setAttribute(AttributeKey::COMMENTS, $oldNode->getAttribute(AttributeKey::COMMENTS));
}
}
/**
* @param Node[] $mergedNodes
*/
public function keepComments(Node $newNode, array $mergedNodes): void
{
$comments = $newNode->getComments();
foreach ($mergedNodes as $mergedNode) {
$comments = array_merge($comments, $mergedNode->getComments());
}
if ($comments === []) {
return;
}
$newNode->setAttribute(AttributeKey::COMMENTS, $comments);
// remove so comments "win"
$newNode->setAttribute(AttributeKey::PHP_DOC_INFO, null);
}
}