Skip to content

Commit cb2fae0

Browse files
committed
Add support for anonymous class trait use docblocks and related tests
1 parent 8be3c3c commit cb2fae0

5 files changed

Lines changed: 311 additions & 28 deletions

File tree

‎src/Internal/Generics/TemplateManager.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -877,7 +877,7 @@ private static function computeClassInheritedBindings(string $actualClassName):
877877
/** @var array<string, TypeNode> $bindings */
878878
$bindings = [];
879879

880-
if (! class_exists($actualClassName) && ! interface_exists($actualClassName) && ! trait_exists($actualClassName)) {
880+
if (! class_exists($actualClassName, false) && ! class_exists($actualClassName) && ! interface_exists($actualClassName) && ! trait_exists($actualClassName)) {
881881
return [];
882882
}
883883

‎src/Internal/Io/StreamWrapper.php‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -825,6 +825,7 @@ private static function extractAndSeedFileMetadata(array $stmts, string $filePat
825825
$namespace = '';
826826
$imports = [];
827827
$classTraitUseDocs = [];
828+
$anonymousTraitUseDocs = [];
828829

829830
$nodesToScan = $stmts;
830831
foreach ($stmts as $stmt) {
@@ -872,6 +873,24 @@ private static function extractAndSeedFileMetadata(array $stmts, string $filePat
872873
}
873874
}
874875

875-
SpecialTypeResolver::seedFileMetadata($filePath, $namespace, $imports, $classTraitUseDocs);
876+
$nodeFinder = new \PhpParser\NodeFinder();
877+
/** @var list<\PhpParser\Node\Stmt\Class_> $anonClasses */
878+
$anonClasses = $nodeFinder->find($stmts, function (\PhpParser\Node $node): bool {
879+
return $node instanceof \PhpParser\Node\Stmt\Class_ && $node->name === null;
880+
});
881+
882+
foreach ($anonClasses as $anonClass) {
883+
$startLine = $anonClass->getStartLine();
884+
foreach ($anonClass->stmts as $classStmt) {
885+
if ($classStmt instanceof \PhpParser\Node\Stmt\TraitUse) {
886+
$doc = $classStmt->getDocComment();
887+
if ($doc !== null) {
888+
$anonymousTraitUseDocs[$startLine][] = $doc->getText();
889+
}
890+
}
891+
}
892+
}
893+
894+
SpecialTypeResolver::seedFileMetadata($filePath, $namespace, $imports, $classTraitUseDocs, $anonymousTraitUseDocs);
876895
}
877896
}

‎src/Internal/Resolver/HierarchyResolver.php‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,8 @@ private static function typeExists(string $className): bool
7171
return self::$classExistsCache[$className];
7272
}
7373

74-
$exists = class_exists($className)
74+
$exists = class_exists($className, false)
75+
|| class_exists($className)
7576
|| interface_exists($className)
7677
|| trait_exists($className)
7778
|| enum_exists($className);

‎src/Internal/Resolver/SpecialTypeResolver.php‎

Lines changed: 175 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -143,13 +143,22 @@ final class SpecialTypeResolver
143143
*/
144144
private static array $classTraitUseDocs = [];
145145

146+
/**
147+
* In-memory cache of anonymous class trait use statement docblocks keyed by file and start line.
148+
*
149+
* @var array<string, array<int, array<int, string>>>
150+
*/
151+
private static array $anonymousTraitUseDocs = [];
152+
146153
/**
147154
* Resets reflection context and dynamic caches. Preserves static file imports.
148155
*/
149156
public static function reset(): void
150157
{
151158
self::$reflectionContextCache = [];
152159
self::$fqcnCache = [];
160+
self::$classTraitUseDocs = [];
161+
self::$anonymousTraitUseDocs = [];
153162
}
154163

155164
/**
@@ -817,16 +826,25 @@ private static function resolveConstantKeyValue(string $fqcn, string $constName)
817826
*
818827
* @param array<string, string> $imports
819828
* @param array<string, array<int, string>> $classTraitUseDocs
829+
* @param array<int, array<int, string>> $anonymousTraitUseDocs
820830
*/
821-
public static function seedFileMetadata(string $fileName, string $namespace, array $imports, array $classTraitUseDocs = []): void
822-
{
831+
public static function seedFileMetadata(
832+
string $fileName,
833+
string $namespace,
834+
array $imports,
835+
array $classTraitUseDocs = [],
836+
array $anonymousTraitUseDocs = []
837+
): void {
823838
if ($fileName !== '') {
824839
$fileName = str_replace('\\', '/', $fileName);
825840
self::$fileNamespaces[$fileName] = $namespace;
826841
self::$fileUseImports[$fileName] = $imports;
827842
foreach ($classTraitUseDocs as $className => $docs) {
828843
self::$classTraitUseDocs[$className] = $docs;
829844
}
845+
if ($anonymousTraitUseDocs !== []) {
846+
self::$anonymousTraitUseDocs[$fileName] = $anonymousTraitUseDocs;
847+
}
830848
}
831849
}
832850

@@ -841,17 +859,61 @@ public static function getClassTraitUseDocs(string $className): array
841859
return self::$classTraitUseDocs[$className];
842860
}
843861

844-
if (! class_exists($className) && ! trait_exists($className)) {
862+
if (! class_exists($className, false) && ! class_exists($className) && ! trait_exists($className)) {
845863
return self::$classTraitUseDocs[$className] = [];
846864
}
847865

848866
try {
849867
$ref = new \ReflectionClass($className);
850868
$fileName = $ref->getFileName();
851-
if ($fileName !== false && file_exists($fileName)) {
852-
$source = file_get_contents($fileName);
853-
if ($source !== false) {
854-
self::parseFileMetadata($fileName, $source);
869+
if ($fileName !== false) {
870+
$normalizedFile = str_replace('\\', '/', $fileName);
871+
872+
if ($ref->isAnonymous()) {
873+
$startLine = $ref->getStartLine();
874+
$endLine = $ref->getEndLine();
875+
876+
if (! isset(self::$anonymousTraitUseDocs[$normalizedFile]) && file_exists($fileName)) {
877+
$source = file_get_contents($fileName);
878+
if ($source !== false) {
879+
self::parseFileMetadata($fileName, $source);
880+
}
881+
}
882+
883+
if (isset(self::$anonymousTraitUseDocs[$normalizedFile][$startLine])) {
884+
return self::$classTraitUseDocs[$className] = self::$anonymousTraitUseDocs[$normalizedFile][$startLine];
885+
}
886+
887+
if (isset(self::$anonymousTraitUseDocs[$normalizedFile])) {
888+
foreach (self::$anonymousTraitUseDocs[$normalizedFile] as $line => $docs) {
889+
if ($line >= $startLine && $line <= $endLine) {
890+
return self::$classTraitUseDocs[$className] = $docs;
891+
}
892+
}
893+
894+
$bestMatch = null;
895+
$minDiff = PHP_INT_MAX;
896+
foreach (self::$anonymousTraitUseDocs[$normalizedFile] as $line => $docs) {
897+
$diff = abs($line - $startLine);
898+
if ($diff <= 5 && $diff < $minDiff) {
899+
$minDiff = $diff;
900+
$bestMatch = $docs;
901+
}
902+
}
903+
904+
if ($bestMatch !== null) {
905+
return self::$classTraitUseDocs[$className] = $bestMatch;
906+
}
907+
}
908+
909+
return self::$classTraitUseDocs[$className] = [];
910+
}
911+
912+
if (file_exists($fileName)) {
913+
$source = file_get_contents($fileName);
914+
if ($source !== false) {
915+
self::parseFileMetadata($fileName, $source);
916+
}
855917
}
856918
}
857919
} catch (\Throwable $e) {
@@ -1079,15 +1141,22 @@ public static function isBuiltInTypeKeyword(string $name): bool
10791141
*/
10801142
public static function parseFileMetadata(string $fileName, string $source): void
10811143
{
1082-
self::$fileNamespaces[$fileName] = '';
1083-
self::$fileUseImports[$fileName] = [];
1144+
$normalizedFile = str_replace('\\', '/', $fileName);
1145+
self::$fileNamespaces[$normalizedFile] = '';
1146+
self::$fileUseImports[$normalizedFile] = [];
1147+
self::$anonymousTraitUseDocs[$normalizedFile] = [];
10841148

10851149
try {
10861150
$tokens = \PhpToken::tokenize($source);
10871151
$count = \count($tokens);
10881152
$namespace = '';
10891153
$imports = [];
1090-
$currentClass = null;
1154+
1155+
/** @var list<array{type: 'named'|'anon', name?: string, line?: int, depth: int}> $classStack */
1156+
$classStack = [];
1157+
/** @var array{type: 'named'|'anon', name?: string, line?: int}|null $pendingClass */
1158+
$pendingClass = null;
1159+
$braceDepth = 0;
10911160

10921161
for ($i = 0; $i < $count; $i++) {
10931162
$token = $tokens[$i];
@@ -1105,35 +1174,116 @@ public static function parseFileMetadata(string $fileName, string $source): void
11051174
}
11061175
}
11071176
$namespace = trim(implode('', $nsParts));
1108-
self::$fileNamespaces[$fileName] = $namespace;
1177+
self::$fileNamespaces[$normalizedFile] = $namespace;
11091178

11101179
continue;
11111180
}
11121181

1113-
if (($token->id === T_CLASS || $token->id === T_INTERFACE || $token->id === T_TRAIT || (\defined('T_ENUM') && $token->id === T_ENUM)) && isset($tokens[$i + 2]) && $tokens[$i + 2]->id === T_STRING) {
1114-
$className = $tokens[$i + 2]->text;
1115-
$currentClass = $namespace !== '' ? $namespace . '\\' . $className : $className;
1116-
self::$classTraitUseDocs[$currentClass] = [];
1182+
$isClassLike = $token->id === T_CLASS || $token->id === T_INTERFACE || $token->id === T_TRAIT || (\defined('T_ENUM') && $token->id === T_ENUM);
1183+
1184+
if ($isClassLike) {
1185+
// Ignore ::class (e.g. Foo::class)
1186+
$isClassConst = false;
1187+
for ($prev = $i - 1; $prev >= 0; $prev--) {
1188+
if ($tokens[$prev]->id === T_WHITESPACE || $tokens[$prev]->id === T_COMMENT) {
1189+
continue;
1190+
}
1191+
if ($tokens[$prev]->id === T_DOUBLE_COLON) {
1192+
$isClassConst = true;
1193+
}
1194+
1195+
break;
1196+
}
1197+
1198+
if ($isClassConst) {
1199+
continue;
1200+
}
1201+
1202+
$nameToken = null;
1203+
for ($j = $i + 1; $j < $count; $j++) {
1204+
if ($tokens[$j]->id === T_WHITESPACE || $tokens[$j]->id === T_COMMENT || $tokens[$j]->id === T_DOC_COMMENT) {
1205+
continue;
1206+
}
1207+
if ($tokens[$j]->id === T_STRING) {
1208+
$nameToken = $tokens[$j];
1209+
}
1210+
1211+
break;
1212+
}
1213+
1214+
if ($nameToken !== null) {
1215+
$className = $namespace !== '' ? $namespace . '\\' . $nameToken->text : $nameToken->text;
1216+
self::$classTraitUseDocs[$className] = [];
1217+
$pendingClass = ['type' => 'named', 'name' => $className];
1218+
} elseif ($token->id === T_CLASS) {
1219+
$pendingClass = ['type' => 'anon', 'line' => $token->line];
1220+
}
11171221

11181222
continue;
11191223
}
11201224

1121-
if ($token->id === T_USE && $currentClass !== null) {
1122-
for ($k = $i - 1; $k >= 0; $k--) {
1123-
if ($tokens[$k]->id === T_DOC_COMMENT) {
1124-
self::$classTraitUseDocs[$currentClass][] = $tokens[$k]->text;
1225+
if ($token->text === '{' || $token->id === T_CURLY_OPEN || $token->id === T_DOLLAR_OPEN_CURLY_BRACES) {
1226+
$braceDepth++;
1227+
if ($pendingClass !== null) {
1228+
$classStack[] = [
1229+
'type' => $pendingClass['type'],
1230+
'name' => $pendingClass['name'] ?? null,
1231+
'line' => $pendingClass['line'] ?? null,
1232+
'depth' => $braceDepth,
1233+
];
1234+
$pendingClass = null;
1235+
}
11251236

1126-
break;
1237+
continue;
1238+
}
1239+
1240+
if ($token->text === '}') {
1241+
if ($classStack !== []) {
1242+
$top = end($classStack);
1243+
if ($braceDepth === $top['depth']) {
1244+
array_pop($classStack);
11271245
}
1128-
if ($tokens[$k]->id !== T_WHITESPACE) {
1129-
break;
1246+
}
1247+
$braceDepth--;
1248+
1249+
continue;
1250+
}
1251+
1252+
if ($token->id === T_USE && $classStack !== []) {
1253+
$isClosureUse = false;
1254+
for ($j = $i + 1; $j < $count; $j++) {
1255+
if ($tokens[$j]->id === T_WHITESPACE || $tokens[$j]->id === T_COMMENT) {
1256+
continue;
1257+
}
1258+
if ($tokens[$j]->text === '(') {
1259+
$isClosureUse = true;
1260+
}
1261+
1262+
break;
1263+
}
1264+
1265+
if (! $isClosureUse) {
1266+
for ($k = $i - 1; $k >= 0; $k--) {
1267+
if ($tokens[$k]->id === T_DOC_COMMENT) {
1268+
$top = end($classStack);
1269+
if ($top['type'] === 'named' && isset($top['name'])) {
1270+
self::$classTraitUseDocs[$top['name']][] = $tokens[$k]->text;
1271+
} elseif ($top['type'] === 'anon' && isset($top['line'])) {
1272+
self::$anonymousTraitUseDocs[$normalizedFile][$top['line']][] = $tokens[$k]->text;
1273+
}
1274+
1275+
break;
1276+
}
1277+
if ($tokens[$k]->id !== T_WHITESPACE) {
1278+
break;
1279+
}
11301280
}
11311281
}
11321282

11331283
continue;
11341284
}
11351285

1136-
if ($token->id === T_USE && $currentClass === null) {
1286+
if ($token->id === T_USE && $classStack === []) {
11371287
$useStatement = '';
11381288
for ($j = $i + 1; $j < $count; $j++) {
11391289
if ($tokens[$j]->text === ';') {
@@ -1189,9 +1339,9 @@ public static function parseFileMetadata(string $fileName, string $source): void
11891339
}
11901340
}
11911341

1192-
self::$fileUseImports[$fileName] = $imports;
1342+
self::$fileUseImports[$normalizedFile] = $imports;
11931343
} catch (\Throwable $e) {
1194-
self::$fileUseImports[$fileName] = [];
1344+
self::$fileUseImports[$normalizedFile] = [];
11951345
}
11961346
}
11971347
}

0 commit comments

Comments
 (0)