diff --git a/src/PhpNodeVisitor.php b/src/PhpNodeVisitor.php index f842eb5..03fc193 100644 --- a/src/PhpNodeVisitor.php +++ b/src/PhpNodeVisitor.php @@ -59,6 +59,13 @@ public function enterNode(Node $node) case 'Expr_Assign': $this->bufferComments[] = $node; break; + default: + // Comments in front of a function call belong to the outermost node starting there, + // e.g. the argument or array item the function call is the value of. + if ($node->getComments()) { + $this->bufferComments[] = $node; + } + break; } return null; @@ -93,8 +100,12 @@ protected function createFunction(Expr $node): ParsedFunction // nikic/php-parser 4 assigns a comment to every node starting after it, not only to the outermost one. $seen = []; - $addComments = static function (Node $commentedNode) use ($function, &$seen): void { + $addComments = static function (Node $commentedNode, ?int $endLine = null) use ($function, &$seen): void { foreach ($commentedNode->getComments() as $comment) { + if ($endLine !== null && $comment->getEndLine() !== $endLine) { + continue; + } + $position = $comment->getStartFilePos(); if (!isset($seen[$position])) { @@ -109,6 +120,9 @@ protected function createFunction(Expr $node): ParsedFunction foreach ($this->bufferComments as $bufferComment) { if ($bufferComment->getStartLine() === $node->getStartLine()) { $addComments($bufferComment); + } else { + // Comments on the line before, e.g. in its own PHP block in a template. + $addComments($bufferComment, $node->getStartLine() - 1); } } diff --git a/tests/PhpFunctionsScannerTest.php b/tests/PhpFunctionsScannerTest.php index ed4463d..2efb776 100644 --- a/tests/PhpFunctionsScannerTest.php +++ b/tests/PhpFunctionsScannerTest.php @@ -188,4 +188,52 @@ public function testPhpFunctionsExtractor() $this->assertSame($file, $function->getFilename()); $this->assertCount(0, $function->getComments()); } + + public function testCommentsOfWrappingNodes() + { + $code = <<<'PHP' + __('Label'), + 'other' => __('Other'), +]; + +echo '

' . + /* translators: Concatenated */ + __('Concatenated') . '

'; +?> + +

+ + + +

+PHP; + + $scanner = new PhpFunctionsScanner(['__', '_e']); + $comments = []; + + foreach ($scanner->scan($code, 'file.php') as $function) { + $comments[$function->getArguments()[0]] = $function->getComments(); + } + + $this->assertSame( + [ + 'Hello %s' => ['translators: %s: Name'], + 'Label' => ['translators: Label'], + 'Other' => [], + 'Concatenated' => ['translators: Concatenated'], + 'Template' => ['translators: Previous block'], + 'No comment' => [], + ], + $comments + ); + } }