Skip to content
Merged
4 changes: 3 additions & 1 deletion src/Language/Visitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,9 @@ public static function visit(object $root, array $visitor, ?array $keyMap = null
];
$inList = $node instanceof NodeList;

$keys = ($inList ? $node : $visitorKeys[$node->kind]) ?? [];
$keys = $inList
? $node
: ($visitorKeys[$node->kind] ?? []);
$index = -1;
$edits = [];
if ($parent !== null) {
Expand Down
77 changes: 77 additions & 0 deletions tests/Language/VisitorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1905,4 +1905,81 @@ public function testThrowsExceptionWhenAddingIntegerToNodeList(): void
]
);
}

public function testVisitCallsGenericVisitorsForCustomKind(): void
{
$customNode = new class([]) extends Node {
public string $kind = 'CustomKind';
};

$visited = [];

self::visitFailingOnWarnings(
$customNode,
[
'enter' => static function (Node $node) use (&$visited): void {
$visited[] = ['enter', $node->kind];
},
'leave' => static function (Node $node) use (&$visited): void {
$visited[] = ['leave', $node->kind];
},
]
);

self::assertSame(
[
['enter', 'CustomKind'],
['leave', 'CustomKind'],
],
$visited
);
}

public function testVisitCallsKindSpecificVisitorForCustomKind(): void
{
$customNode = new class([]) extends Node {
public string $kind = 'CustomKind';
};

$visited = [];

self::visitFailingOnWarnings(
$customNode,
[
'CustomKind' => [
'enter' => static function (Node $node) use (&$visited): void {
$visited[] = ['enter', $node->kind];
},
'leave' => static function (Node $node) use (&$visited): void {
$visited[] = ['leave', $node->kind];
},
],
]
);

self::assertSame(
[
['enter', 'CustomKind'],
['leave', 'CustomKind'],
],
$visited
);
}

/**
* @param array<string, mixed> $visitor
*
* @throws \Exception
*/
private static function visitFailingOnWarnings(Node $root, array $visitor): void
{
set_error_handler(static function (int $severity, string $message): bool {
throw new \ErrorException($message, 0, $severity);
});
try {
Visitor::visit($root, $visitor);
} finally {
restore_error_handler();
}
}
}
Loading