1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type;
4:
5: use Closure;
6: use PhpParser\Node;
7: use PHPStan\Analyser\NameScope;
8: use PHPStan\BetterReflection\Util\GetLastDocComment;
9: use PHPStan\Broker\AnonymousClassNameHelper;
10: use PHPStan\File\FileHelper;
11: use PHPStan\Parser\Parser;
12: use PHPStan\PhpDoc\PhpDocNodeResolver;
13: use PHPStan\PhpDoc\PhpDocStringResolver;
14: use PHPStan\PhpDoc\ResolvedPhpDocBlock;
15: use PHPStan\PhpDoc\Tag\TemplateTag;
16: use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocNode;
17: use PHPStan\Reflection\ReflectionProvider\ReflectionProviderProvider;
18: use PHPStan\ShouldNotHappenException;
19: use PHPStan\Type\Generic\GenericObjectType;
20: use PHPStan\Type\Generic\TemplateTypeFactory;
21: use PHPStan\Type\Generic\TemplateTypeHelper;
22: use PHPStan\Type\Generic\TemplateTypeMap;
23: use PHPStan\Type\Generic\TemplateTypeVariance;
24: use PHPStan\Type\Generic\TemplateTypeVarianceMap;
25: use function array_key_exists;
26: use function array_keys;
27: use function array_map;
28: use function array_merge;
29: use function array_pop;
30: use function array_slice;
31: use function count;
32: use function is_array;
33: use function is_callable;
34: use function is_file;
35: use function ltrim;
36: use function md5;
37: use function sprintf;
38: use function str_contains;
39: use function strtolower;
40:
41: class FileTypeMapper
42: {
43:
44: private const SKIP_NODE = 1;
45: private const POP_TYPE_MAP_STACK = 2;
46:
47: /** @var NameScope[][] */
48: private array $memoryCache = [];
49:
50: private int $memoryCacheCount = 0;
51:
52: /** @var (true|callable(): NameScope|NameScope)[][] */
53: private array $inProcess = [];
54:
55: /** @var array<string, ResolvedPhpDocBlock> */
56: private array $resolvedPhpDocBlockCache = [];
57:
58: private int $resolvedPhpDocBlockCacheCount = 0;
59:
60: public function __construct(
61: private ReflectionProviderProvider $reflectionProviderProvider,
62: private Parser $phpParser,
63: private PhpDocStringResolver $phpDocStringResolver,
64: private PhpDocNodeResolver $phpDocNodeResolver,
65: private AnonymousClassNameHelper $anonymousClassNameHelper,
66: private FileHelper $fileHelper,
67: )
68: {
69: }
70:
71: /** @api */
72: public function getResolvedPhpDoc(
73: ?string $fileName,
74: ?string $className,
75: ?string $traitName,
76: ?string $functionName,
77: string $docComment,
78: ): ResolvedPhpDocBlock
79: {
80: if ($className === null && $traitName !== null) {
81: throw new ShouldNotHappenException();
82: }
83:
84: if ($docComment === '') {
85: return ResolvedPhpDocBlock::createEmpty();
86: }
87:
88: if ($fileName !== null) {
89: $fileName = $this->fileHelper->normalizePath($fileName);
90: }
91:
92: $nameScopeKey = $this->getNameScopeKey($fileName, $className, $traitName, $functionName);
93: $phpDocKey = md5(sprintf('%s-%s', $nameScopeKey, $docComment));
94: if (isset($this->resolvedPhpDocBlockCache[$phpDocKey])) {
95: return $this->resolvedPhpDocBlockCache[$phpDocKey];
96: }
97:
98: if ($fileName === null) {
99: return $this->createResolvedPhpDocBlock($phpDocKey, new NameScope(null, []), $docComment, null);
100: }
101:
102: $nameScopeMap = [];
103:
104: if (!isset($this->inProcess[$fileName])) {
105: $nameScopeMap = $this->getNameScopeMap($fileName);
106: }
107:
108: if (isset($nameScopeMap[$nameScopeKey])) {
109: return $this->createResolvedPhpDocBlock($phpDocKey, $nameScopeMap[$nameScopeKey], $docComment, $fileName);
110: }
111:
112: if (!isset($this->inProcess[$fileName][$nameScopeKey])) { // wrong $fileName due to traits
113: return ResolvedPhpDocBlock::createEmpty();
114: }
115:
116: if ($this->inProcess[$fileName][$nameScopeKey] === true) { // PHPDoc has cyclic dependency
117: return ResolvedPhpDocBlock::createEmpty();
118: }
119:
120: if (is_callable($this->inProcess[$fileName][$nameScopeKey])) {
121: $resolveCallback = $this->inProcess[$fileName][$nameScopeKey];
122: $this->inProcess[$fileName][$nameScopeKey] = true;
123: $this->inProcess[$fileName][$nameScopeKey] = $resolveCallback();
124: }
125:
126: return $this->createResolvedPhpDocBlock($phpDocKey, $this->inProcess[$fileName][$nameScopeKey], $docComment, $fileName);
127: }
128:
129: private function createResolvedPhpDocBlock(string $phpDocKey, NameScope $nameScope, string $phpDocString, ?string $fileName): ResolvedPhpDocBlock
130: {
131: $phpDocNode = $this->phpDocStringResolver->resolve($phpDocString);
132: if ($this->resolvedPhpDocBlockCacheCount >= 2048) {
133: $this->resolvedPhpDocBlockCache = array_slice(
134: $this->resolvedPhpDocBlockCache,
135: 1,
136: null,
137: true,
138: );
139:
140: $this->resolvedPhpDocBlockCacheCount--;
141: }
142:
143: $templateTypeMap = $nameScope->getTemplateTypeMap();
144: $phpDocTemplateTypes = [];
145: $templateTags = $this->phpDocNodeResolver->resolveTemplateTags($phpDocNode, $nameScope);
146: foreach (array_keys($templateTags) as $name) {
147: $templateType = $templateTypeMap->getType($name);
148: if ($templateType === null) {
149: continue;
150: }
151: $phpDocTemplateTypes[$name] = $templateType;
152: }
153:
154: $this->resolvedPhpDocBlockCache[$phpDocKey] = ResolvedPhpDocBlock::create(
155: $phpDocNode,
156: $phpDocString,
157: $fileName,
158: $nameScope,
159: new TemplateTypeMap($phpDocTemplateTypes),
160: $templateTags,
161: $this->phpDocNodeResolver,
162: $this->reflectionProviderProvider->getReflectionProvider(),
163: );
164: $this->resolvedPhpDocBlockCacheCount++;
165:
166: return $this->resolvedPhpDocBlockCache[$phpDocKey];
167: }
168:
169: /**
170: * @return NameScope[]
171: */
172: private function getNameScopeMap(string $fileName): array
173: {
174: if (!isset($this->memoryCache[$fileName])) {
175: $map = $this->createResolvedPhpDocMap($fileName);
176: if ($this->memoryCacheCount >= 2048) {
177: $this->memoryCache = array_slice(
178: $this->memoryCache,
179: 1,
180: null,
181: true,
182: );
183: $this->memoryCacheCount--;
184: }
185:
186: $this->memoryCache[$fileName] = $map;
187: $this->memoryCacheCount++;
188: }
189:
190: return $this->memoryCache[$fileName];
191: }
192:
193: /**
194: * @return NameScope[]
195: */
196: private function createResolvedPhpDocMap(string $fileName): array
197: {
198: $phpDocNodeMap = $this->createPhpDocNodeMap($fileName, null, $fileName, [], $fileName);
199: $nameScopeMap = $this->createNameScopeMap($fileName, null, null, [], $fileName, $phpDocNodeMap);
200: $resolvedNameScopeMap = [];
201:
202: try {
203: $this->inProcess[$fileName] = $nameScopeMap;
204:
205: foreach ($nameScopeMap as $nameScopeKey => $resolveCallback) {
206: $this->inProcess[$fileName][$nameScopeKey] = true;
207: $this->inProcess[$fileName][$nameScopeKey] = $data = $resolveCallback();
208: $resolvedNameScopeMap[$nameScopeKey] = $data;
209: }
210:
211: } finally {
212: unset($this->inProcess[$fileName]);
213: }
214:
215: return $resolvedNameScopeMap;
216: }
217:
218: /**
219: * @param array<string, string> $traitMethodAliases
220: * @return array<string, PhpDocNode>
221: */
222: private function createPhpDocNodeMap(string $fileName, ?string $lookForTrait, ?string $traitUseClass, array $traitMethodAliases, string $originalClassFileName): array
223: {
224: /** @var array<string, PhpDocNode> $phpDocNodeMap */
225: $phpDocNodeMap = [];
226:
227: /** @var string[] $classStack */
228: $classStack = [];
229: if ($lookForTrait !== null && $traitUseClass !== null) {
230: $classStack[] = $traitUseClass;
231: }
232: $namespace = null;
233:
234: $traitFound = false;
235:
236: /** @var array<string|null> $functionStack */
237: $functionStack = [];
238: $this->processNodes(
239: $this->phpParser->parseFile($fileName),
240: function (Node $node) use ($fileName, $lookForTrait, &$traitFound, $traitMethodAliases, $originalClassFileName, &$phpDocNodeMap, &$classStack, &$namespace, &$functionStack): ?int {
241: if ($node instanceof Node\Stmt\ClassLike) {
242: if ($traitFound && $fileName === $originalClassFileName) {
243: return self::SKIP_NODE;
244: }
245:
246: if ($lookForTrait !== null && !$traitFound) {
247: if (!$node instanceof Node\Stmt\Trait_) {
248: return self::SKIP_NODE;
249: }
250: if ((string) $node->namespacedName !== $lookForTrait) {
251: return self::SKIP_NODE;
252: }
253:
254: $traitFound = true;
255: $functionStack[] = null;
256: } else {
257: if ($node->name === null) {
258: if (!$node instanceof Node\Stmt\Class_) {
259: throw new ShouldNotHappenException();
260: }
261:
262: $className = $this->anonymousClassNameHelper->getAnonymousClassName($node, $fileName);
263: } elseif ((bool) $node->getAttribute('anonymousClass', false)) {
264: $className = $node->name->name;
265: } else {
266: if ($traitFound) {
267: return self::SKIP_NODE;
268: }
269: $className = ltrim(sprintf('%s\\%s', $namespace, $node->name->name), '\\');
270: }
271: $classStack[] = $className;
272: $functionStack[] = null;
273: }
274: } elseif ($node instanceof Node\Stmt\ClassMethod) {
275: if (array_key_exists($node->name->name, $traitMethodAliases)) {
276: $functionStack[] = $traitMethodAliases[$node->name->name];
277: } else {
278: $functionStack[] = $node->name->name;
279: }
280: } elseif ($node instanceof Node\Stmt\Function_) {
281: $functionStack[] = ltrim(sprintf('%s\\%s', $namespace, $node->name->name), '\\');
282: }
283:
284: $className = $classStack[count($classStack) - 1] ?? null;
285: $functionName = $functionStack[count($functionStack) - 1] ?? null;
286:
287: if ($node instanceof Node\Stmt\ClassLike || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Stmt\Function_) {
288: $docComment = GetLastDocComment::forNode($node);
289: if ($docComment !== null) {
290: $nameScopeKey = $this->getNameScopeKey($originalClassFileName, $className, $lookForTrait, $functionName);
291: $phpDocNodeMap[$nameScopeKey] = $this->phpDocStringResolver->resolve($docComment);
292: }
293:
294: return null;
295: }
296:
297: if ($node instanceof Node\Stmt\Namespace_) {
298: $namespace = $node->name !== null ? (string) $node->name : null;
299: } elseif ($node instanceof Node\Stmt\TraitUse) {
300: $traitMethodAliases = [];
301: foreach ($node->adaptations as $traitUseAdaptation) {
302: if (!$traitUseAdaptation instanceof Node\Stmt\TraitUseAdaptation\Alias) {
303: continue;
304: }
305:
306: if ($traitUseAdaptation->newName === null) {
307: continue;
308: }
309:
310: $methodName = $traitUseAdaptation->method->toString();
311: $newTraitName = $traitUseAdaptation->newName->toString();
312:
313: if ($traitUseAdaptation->trait === null) {
314: foreach ($node->traits as $traitName) {
315: $traitMethodAliases[$traitName->toString()][$methodName] = $newTraitName;
316: }
317: continue;
318: }
319:
320: $traitMethodAliases[$traitUseAdaptation->trait->toString()][$methodName] = $newTraitName;
321: }
322:
323: foreach ($node->traits as $traitName) {
324: /** @var class-string $traitName */
325: $traitName = (string) $traitName;
326: $reflectionProvider = $this->reflectionProviderProvider->getReflectionProvider();
327: if (!$reflectionProvider->hasClass($traitName)) {
328: continue;
329: }
330:
331: $traitReflection = $reflectionProvider->getClass($traitName);
332: if (!$traitReflection->isTrait()) {
333: continue;
334: }
335: if ($traitReflection->getFileName() === null) {
336: continue;
337: }
338: if (!is_file($traitReflection->getFileName())) {
339: continue;
340: }
341:
342: $className = $classStack[count($classStack) - 1] ?? null;
343: if ($className === null) {
344: throw new ShouldNotHappenException();
345: }
346:
347: $phpDocNodeMap = array_merge($phpDocNodeMap, $this->createPhpDocNodeMap(
348: $traitReflection->getFileName(),
349: $traitName,
350: $className,
351: $traitMethodAliases[$traitName] ?? [],
352: $originalClassFileName,
353: ));
354: }
355: }
356:
357: return null;
358: },
359: static function (Node $node) use (&$namespace, &$functionStack, &$classStack): void {
360: if ($node instanceof Node\Stmt\ClassLike) {
361: if (count($classStack) === 0) {
362: throw new ShouldNotHappenException();
363: }
364: array_pop($classStack);
365:
366: if (count($functionStack) === 0) {
367: throw new ShouldNotHappenException();
368: }
369:
370: array_pop($functionStack);
371: } elseif ($node instanceof Node\Stmt\Namespace_) {
372: $namespace = null;
373: } elseif ($node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Stmt\Function_) {
374: if (count($functionStack) === 0) {
375: throw new ShouldNotHappenException();
376: }
377:
378: array_pop($functionStack);
379: }
380: },
381: );
382:
383: return $phpDocNodeMap;
384: }
385:
386: /**
387: * @param array<string, string> $traitMethodAliases
388: * @param array<string, PhpDocNode> $phpDocNodeMap
389: * @return (callable(): NameScope)[]
390: */
391: private function createNameScopeMap(
392: string $fileName,
393: ?string $lookForTrait,
394: ?string $traitUseClass,
395: array $traitMethodAliases,
396: string $originalClassFileName,
397: array $phpDocNodeMap,
398: ): array
399: {
400: /** @var (callable(): NameScope)[] $nameScopeMap */
401: $nameScopeMap = [];
402:
403: /** @var (callable(): TemplateTypeMap)[] $typeMapStack */
404: $typeMapStack = [];
405:
406: /** @var array<int, array<string, true>> $typeAliasStack */
407: $typeAliasStack = [];
408:
409: /** @var string[] $classStack */
410: $classStack = [];
411: if ($lookForTrait !== null && $traitUseClass !== null) {
412: $classStack[] = $traitUseClass;
413: $typeAliasStack[] = [];
414: }
415: $namespace = null;
416:
417: $traitFound = false;
418:
419: /** @var array<string|null> $functionStack */
420: $functionStack = [];
421: $uses = [];
422: $constUses = [];
423: $this->processNodes(
424: $this->phpParser->parseFile($fileName),
425: function (Node $node) use ($fileName, $lookForTrait, $phpDocNodeMap, &$traitFound, $traitMethodAliases, $originalClassFileName, &$nameScopeMap, &$classStack, &$typeAliasStack, &$namespace, &$functionStack, &$uses, &$typeMapStack, &$constUses): ?int {
426: if ($node instanceof Node\Stmt\ClassLike) {
427: if ($traitFound && $fileName === $originalClassFileName) {
428: return self::SKIP_NODE;
429: }
430:
431: if ($lookForTrait !== null && !$traitFound) {
432: if (!$node instanceof Node\Stmt\Trait_) {
433: return self::SKIP_NODE;
434: }
435: if ((string) $node->namespacedName !== $lookForTrait) {
436: return self::SKIP_NODE;
437: }
438:
439: $traitFound = true;
440: $traitNameScopeKey = $this->getNameScopeKey($originalClassFileName, $classStack[count($classStack) - 1] ?? null, $lookForTrait, null);
441: if (array_key_exists($traitNameScopeKey, $phpDocNodeMap)) {
442: $typeAliasStack[] = $this->getTypeAliasesMap($phpDocNodeMap[$traitNameScopeKey]);
443: } else {
444: $typeAliasStack[] = [];
445: }
446: $functionStack[] = null;
447: } else {
448: if ($node->name === null) {
449: if (!$node instanceof Node\Stmt\Class_) {
450: throw new ShouldNotHappenException();
451: }
452:
453: $className = $this->anonymousClassNameHelper->getAnonymousClassName($node, $fileName);
454: } elseif ((bool) $node->getAttribute('anonymousClass', false)) {
455: $className = $node->name->name;
456: } else {
457: if ($traitFound) {
458: return self::SKIP_NODE;
459: }
460: $className = ltrim(sprintf('%s\\%s', $namespace, $node->name->name), '\\');
461: }
462: $classStack[] = $className;
463: $classNameScopeKey = $this->getNameScopeKey($originalClassFileName, $className, $lookForTrait, null);
464: if (array_key_exists($classNameScopeKey, $phpDocNodeMap)) {
465: $typeAliasStack[] = $this->getTypeAliasesMap($phpDocNodeMap[$classNameScopeKey]);
466: } else {
467: $typeAliasStack[] = [];
468: }
469: $functionStack[] = null;
470: }
471: } elseif ($node instanceof Node\Stmt\ClassMethod) {
472: if (array_key_exists($node->name->name, $traitMethodAliases)) {
473: $functionStack[] = $traitMethodAliases[$node->name->name];
474: } else {
475: $functionStack[] = $node->name->name;
476: }
477: } elseif ($node instanceof Node\Stmt\Function_) {
478: $functionStack[] = ltrim(sprintf('%s\\%s', $namespace, $node->name->name), '\\');
479: }
480:
481: $className = $classStack[count($classStack) - 1] ?? null;
482: $functionName = $functionStack[count($functionStack) - 1] ?? null;
483: $nameScopeKey = $this->getNameScopeKey($originalClassFileName, $className, $lookForTrait, $functionName);
484:
485: if ($namespace === '') {
486: throw new ShouldNotHappenException('Namespace cannot be empty.');
487: }
488:
489: if ($node instanceof Node\Stmt\ClassLike || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Stmt\Function_) {
490: if (array_key_exists($nameScopeKey, $phpDocNodeMap)) {
491: $phpDocNode = $phpDocNodeMap[$nameScopeKey];
492: $typeMapStack[] = function () use ($namespace, $uses, $className, $lookForTrait, $functionName, $phpDocNode, $typeMapStack, $typeAliasStack, $constUses): TemplateTypeMap {
493: $typeMapCb = $typeMapStack[count($typeMapStack) - 1] ?? null;
494: $currentTypeMap = $typeMapCb !== null ? $typeMapCb() : null;
495: $typeAliasesMap = $typeAliasStack[count($typeAliasStack) - 1] ?? [];
496: $nameScope = new NameScope($namespace, $uses, $className, $functionName, $currentTypeMap, $typeAliasesMap, false, $constUses, $lookForTrait);
497: $templateTags = $this->phpDocNodeResolver->resolveTemplateTags($phpDocNode, $nameScope);
498: $templateTypeScope = $nameScope->getTemplateTypeScope();
499: if ($templateTypeScope === null) {
500: throw new ShouldNotHappenException();
501: }
502: $templateTypeMap = new TemplateTypeMap(array_map(static fn (TemplateTag $tag): Type => TemplateTypeFactory::fromTemplateTag($templateTypeScope, $tag), $templateTags));
503: $nameScope = $nameScope->withTemplateTypeMap($templateTypeMap);
504: $templateTags = $this->phpDocNodeResolver->resolveTemplateTags($phpDocNode, $nameScope);
505: $templateTypeMap = new TemplateTypeMap(array_map(static fn (TemplateTag $tag): Type => TemplateTypeFactory::fromTemplateTag($templateTypeScope, $tag), $templateTags));
506:
507: return new TemplateTypeMap(array_merge(
508: $currentTypeMap !== null ? $currentTypeMap->getTypes() : [],
509: $templateTypeMap->getTypes(),
510: ));
511: };
512: }
513: }
514:
515: $typeMapCb = $typeMapStack[count($typeMapStack) - 1] ?? null;
516: $typeAliasesMap = $typeAliasStack[count($typeAliasStack) - 1] ?? [];
517:
518: if (
519: $node instanceof Node\Stmt
520: && !$node instanceof Node\Stmt\Namespace_
521: && !$node instanceof Node\Stmt\Declare_
522: && !$node instanceof Node\Stmt\DeclareDeclare
523: && !$node instanceof Node\Stmt\Use_
524: && !$node instanceof Node\Stmt\UseUse
525: && !$node instanceof Node\Stmt\GroupUse
526: && !$node instanceof Node\Stmt\TraitUse
527: && !$node instanceof Node\Stmt\TraitUseAdaptation
528: && !$node instanceof Node\Stmt\InlineHTML
529: && !($node instanceof Node\Stmt\Expression && $node->expr instanceof Node\Expr\Include_)
530: && !array_key_exists($nameScopeKey, $nameScopeMap)
531: ) {
532: $nameScopeMap[$nameScopeKey] = static fn (): NameScope => new NameScope(
533: $namespace,
534: $uses,
535: $className,
536: $functionName,
537: ($typeMapCb !== null ? $typeMapCb() : TemplateTypeMap::createEmpty()),
538: $typeAliasesMap,
539: false,
540: $constUses,
541: $lookForTrait,
542: );
543: }
544:
545: if ($node instanceof Node\Stmt\ClassLike || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Stmt\Function_) {
546: if (array_key_exists($nameScopeKey, $phpDocNodeMap)) {
547: return self::POP_TYPE_MAP_STACK;
548: }
549:
550: return null;
551: }
552:
553: if ($node instanceof Node\Stmt\Namespace_) {
554: $namespace = $node->name !== null ? (string) $node->name : null;
555: } elseif ($node instanceof Node\Stmt\Use_) {
556: if ($node->type === Node\Stmt\Use_::TYPE_NORMAL) {
557: foreach ($node->uses as $use) {
558: $uses[strtolower($use->getAlias()->name)] = (string) $use->name;
559: }
560: } elseif ($node->type === Node\Stmt\Use_::TYPE_CONSTANT) {
561: foreach ($node->uses as $use) {
562: $constUses[strtolower($use->getAlias()->name)] = (string) $use->name;
563: }
564: }
565: } elseif ($node instanceof Node\Stmt\GroupUse) {
566: $prefix = (string) $node->prefix;
567: foreach ($node->uses as $use) {
568: if ($node->type === Node\Stmt\Use_::TYPE_NORMAL || $use->type === Node\Stmt\Use_::TYPE_NORMAL) {
569: $uses[strtolower($use->getAlias()->name)] = sprintf('%s\\%s', $prefix, (string) $use->name);
570: } elseif ($node->type === Node\Stmt\Use_::TYPE_CONSTANT || $use->type === Node\Stmt\Use_::TYPE_CONSTANT) {
571: $constUses[strtolower($use->getAlias()->name)] = sprintf('%s\\%s', $prefix, (string) $use->name);
572: }
573: }
574: } elseif ($node instanceof Node\Stmt\TraitUse) {
575: $traitMethodAliases = [];
576: foreach ($node->adaptations as $traitUseAdaptation) {
577: if (!$traitUseAdaptation instanceof Node\Stmt\TraitUseAdaptation\Alias) {
578: continue;
579: }
580:
581: if ($traitUseAdaptation->newName === null) {
582: continue;
583: }
584:
585: $methodName = $traitUseAdaptation->method->toString();
586: $newTraitName = $traitUseAdaptation->newName->toString();
587:
588: if ($traitUseAdaptation->trait === null) {
589: foreach ($node->traits as $traitName) {
590: $traitMethodAliases[$traitName->toString()][$methodName] = $newTraitName;
591: }
592: continue;
593: }
594:
595: $traitMethodAliases[$traitUseAdaptation->trait->toString()][$methodName] = $newTraitName;
596: }
597:
598: $useDocComment = null;
599: if ($node->getDocComment() !== null) {
600: $useDocComment = $node->getDocComment()->getText();
601: }
602:
603: foreach ($node->traits as $traitName) {
604: /** @var class-string $traitName */
605: $traitName = (string) $traitName;
606: $reflectionProvider = $this->reflectionProviderProvider->getReflectionProvider();
607: if (!$reflectionProvider->hasClass($traitName)) {
608: continue;
609: }
610:
611: $traitReflection = $reflectionProvider->getClass($traitName);
612: if (!$traitReflection->isTrait()) {
613: continue;
614: }
615: if ($traitReflection->getFileName() === null) {
616: continue;
617: }
618: if (!is_file($traitReflection->getFileName())) {
619: continue;
620: }
621:
622: $className = $classStack[count($classStack) - 1] ?? null;
623: if ($className === null) {
624: throw new ShouldNotHappenException();
625: }
626:
627: $traitPhpDocMap = $this->createNameScopeMap(
628: $traitReflection->getFileName(),
629: $traitName,
630: $className,
631: $traitMethodAliases[$traitName] ?? [],
632: $originalClassFileName,
633: $phpDocNodeMap,
634: );
635: $finalTraitPhpDocMap = [];
636: foreach ($traitPhpDocMap as $nameScopeTraitKey => $callback) {
637: $finalTraitPhpDocMap[$nameScopeTraitKey] = function () use ($callback, $traitReflection, $fileName, $className, $lookForTrait, $useDocComment): NameScope {
638: /** @var NameScope $original */
639: $original = $callback();
640: if (!$traitReflection->isGeneric()) {
641: return $original;
642: }
643:
644: $traitTemplateTypeMap = $traitReflection->getTemplateTypeMap();
645:
646: $useType = null;
647: if ($useDocComment !== null) {
648: $useTags = $this->getResolvedPhpDoc(
649: $fileName,
650: $className,
651: $lookForTrait,
652: null,
653: $useDocComment,
654: )->getUsesTags();
655: foreach ($useTags as $useTag) {
656: $useTagType = $useTag->getType();
657: if (!$useTagType instanceof GenericObjectType) {
658: continue;
659: }
660:
661: if ($useTagType->getClassName() !== $traitReflection->getName()) {
662: continue;
663: }
664:
665: $useType = $useTagType;
666: break;
667: }
668: }
669:
670: if ($useType === null) {
671: return $original->withTemplateTypeMap($traitTemplateTypeMap->resolveToBounds());
672: }
673:
674: $transformedTraitTypeMap = $traitReflection->typeMapFromList($useType->getTypes());
675:
676: return $original->withTemplateTypeMap($traitTemplateTypeMap->map(static fn (string $name, Type $type): Type => TemplateTypeHelper::resolveTemplateTypes($type, $transformedTraitTypeMap, TemplateTypeVarianceMap::createEmpty(), TemplateTypeVariance::createStatic())));
677: };
678: }
679: $nameScopeMap = array_merge($nameScopeMap, $finalTraitPhpDocMap);
680: }
681: }
682:
683: return null;
684: },
685: static function (Node $node, $callbackResult) use (&$namespace, &$functionStack, &$classStack, &$typeAliasStack, &$uses, &$typeMapStack, &$constUses): void {
686: if ($node instanceof Node\Stmt\ClassLike) {
687: if (count($classStack) === 0) {
688: throw new ShouldNotHappenException();
689: }
690: array_pop($classStack);
691:
692: if (count($typeAliasStack) === 0) {
693: throw new ShouldNotHappenException();
694: }
695:
696: array_pop($typeAliasStack);
697:
698: if (count($functionStack) === 0) {
699: throw new ShouldNotHappenException();
700: }
701:
702: array_pop($functionStack);
703: } elseif ($node instanceof Node\Stmt\Namespace_) {
704: $namespace = null;
705: $uses = [];
706: $constUses = [];
707: } elseif ($node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Stmt\Function_) {
708: if (count($functionStack) === 0) {
709: throw new ShouldNotHappenException();
710: }
711:
712: array_pop($functionStack);
713: }
714: if ($callbackResult !== self::POP_TYPE_MAP_STACK) {
715: return;
716: }
717:
718: if (count($typeMapStack) === 0) {
719: throw new ShouldNotHappenException();
720: }
721: array_pop($typeMapStack);
722: },
723: );
724:
725: if (count($typeMapStack) > 0) {
726: throw new ShouldNotHappenException();
727: }
728:
729: return $nameScopeMap;
730: }
731:
732: /**
733: * @return array<string, true>
734: */
735: private function getTypeAliasesMap(PhpDocNode $phpDocNode): array
736: {
737: $nameScope = new NameScope(null, []);
738:
739: $aliasesMap = [];
740: foreach (array_keys($this->phpDocNodeResolver->resolveTypeAliasImportTags($phpDocNode, $nameScope)) as $key) {
741: $aliasesMap[$key] = true;
742: }
743:
744: foreach (array_keys($this->phpDocNodeResolver->resolveTypeAliasTags($phpDocNode, $nameScope)) as $key) {
745: $aliasesMap[$key] = true;
746: }
747:
748: return $aliasesMap;
749: }
750:
751: /**
752: * @param Node[]|Node|scalar|null $node
753: * @param Closure(Node $node): mixed $nodeCallback
754: * @param Closure(Node $node, mixed $callbackResult): void $endNodeCallback
755: */
756: private function processNodes($node, Closure $nodeCallback, Closure $endNodeCallback): void
757: {
758: if ($node instanceof Node) {
759: $callbackResult = $nodeCallback($node);
760: if ($callbackResult === self::SKIP_NODE) {
761: return;
762: }
763: foreach ($node->getSubNodeNames() as $subNodeName) {
764: $subNode = $node->{$subNodeName};
765: $this->processNodes($subNode, $nodeCallback, $endNodeCallback);
766: }
767: $endNodeCallback($node, $callbackResult);
768: } elseif (is_array($node)) {
769: foreach ($node as $subNode) {
770: $this->processNodes($subNode, $nodeCallback, $endNodeCallback);
771: }
772: }
773: }
774:
775: private function getNameScopeKey(
776: ?string $file,
777: ?string $class,
778: ?string $trait,
779: ?string $function,
780: ): string
781: {
782: if ($class === null && $trait === null && $function === null) {
783: return md5(sprintf('%s', $file ?? 'no-file'));
784: }
785:
786: if ($class !== null && str_contains($class, 'class@anonymous')) {
787: throw new ShouldNotHappenException('Wrong anonymous class name, FilTypeMapper should be called with ClassReflection::getName().');
788: }
789:
790: return md5(sprintf('%s-%s-%s-%s', $file ?? 'no-file', $class, $trait, $function));
791: }
792:
793: }
794: