1: <?php declare(strict_types=1);
2:
3: namespace PhpParser\NodeVisitor;
4:
5: use PhpParser\Comment;
6: use PhpParser\Node;
7: use PhpParser\NodeVisitorAbstract;
8: use PhpParser\Token;
9:
10: class CommentAnnotatingVisitor extends NodeVisitorAbstract {
11: /** @var int Last seen token start position */
12: private int $pos = 0;
13: /** @var Token[] Token array */
14: private array $tokens;
15: /** @var list<int> Token positions of comments */
16: private array $commentPositions = [];
17:
18: /**
19: * Create a comment annotation visitor.
20: *
21: * @param Token[] $tokens Token array
22: */
23: public function __construct(array $tokens) {
24: $this->tokens = $tokens;
25:
26: // Collect positions of comments. We use this to avoid traversing parts of the AST where
27: // there are no comments.
28: foreach ($tokens as $i => $token) {
29: $id = $token->id;
30: if ($id === \T_COMMENT || $id === \T_DOC_COMMENT) {
31: $this->commentPositions[] = $i;
32: }
33: }
34: }
35:
36: public function enterNode(Node $node) {
37: $nextCommentPos = current($this->commentPositions);
38: if ($nextCommentPos === false) {
39: // No more comments.
40: return self::STOP_TRAVERSAL;
41: }
42:
43: $oldPos = $this->pos;
44: $this->pos = $pos = $node->getStartTokenPos();
45: if ($nextCommentPos > $oldPos && $nextCommentPos < $pos) {
46: $comments = [];
47: while (--$pos >= $oldPos) {
48: $token = $this->tokens[$pos];
49: if ($token->id === \T_DOC_COMMENT) {
50: $comments[] = new Comment\Doc(
51: $token->text, $token->line, $token->pos, $pos,
52: $token->getEndLine(), $token->getEndPos() - 1, $pos);
53: continue;
54: }
55: if ($token->id === \T_COMMENT) {
56: $comments[] = new Comment(
57: $token->text, $token->line, $token->pos, $pos,
58: $token->getEndLine(), $token->getEndPos() - 1, $pos);
59: continue;
60: }
61: if ($token->id !== \T_WHITESPACE) {
62: break;
63: }
64: }
65: if (!empty($comments)) {
66: $node->setAttribute('comments', array_reverse($comments));
67: }
68:
69: do {
70: $nextCommentPos = next($this->commentPositions);
71: } while ($nextCommentPos !== false && $nextCommentPos < $this->pos);
72: }
73:
74: $endPos = $node->getEndTokenPos();
75: if ($nextCommentPos > $endPos) {
76: // Skip children if there are no comments located inside this node.
77: $this->pos = $endPos;
78: return self::DONT_TRAVERSE_CHILDREN;
79: }
80:
81: return null;
82: }
83: }
84: