Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion src/PhpNodeVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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])) {
Expand All @@ -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);
}
}

Expand Down
48 changes: 48 additions & 0 deletions tests/PhpFunctionsScannerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,4 +188,52 @@ public function testPhpFunctionsExtractor()
$this->assertSame($file, $function->getFilename());
$this->assertCount(0, $function->getComments());
}

public function testCommentsOfWrappingNodes()
{
$code = <<<'PHP'
<?php
printf(
/* translators: %s: Name */
__('Hello %s'),
$name
);

$labels = [
// translators: Label
'label' => __('Label'),
'other' => __('Other'),
];

echo '<p>' .
/* translators: Concatenated */
__('Concatenated') . '</p>';
?>
<?php /* translators: Previous block */ ?>
<p><?php _e('Template'); ?></p>

<?php /* translators: Too far away */ ?>

<p><?php _e('No comment'); ?></p>
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
);
}
}
Loading