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 ($node instanceof Node\Stmt\ClassLike || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Stmt\Function_) {
486: if (array_key_exists($nameScopeKey, $phpDocNodeMap)) {
487: $phpDocNode = $phpDocNodeMap[$nameScopeKey];
488: $typeMapStack[] = function () use ($namespace, $uses, $className, $lookForTrait, $functionName, $phpDocNode, $typeMapStack, $typeAliasStack, $constUses): TemplateTypeMap {
489: $typeMapCb = $typeMapStack[count($typeMapStack) - 1] ?? null;
490: $currentTypeMap = $typeMapCb !== null ? $typeMapCb() : null;
491: $typeAliasesMap = $typeAliasStack[count($typeAliasStack) - 1] ?? [];
492: $nameScope = new NameScope($namespace, $uses, $className, $functionName, $currentTypeMap, $typeAliasesMap, false, $constUses, $lookForTrait);
493: $templateTags = $this->phpDocNodeResolver->resolveTemplateTags($phpDocNode, $nameScope);
494: $templateTypeScope = $nameScope->getTemplateTypeScope();
495: if ($templateTypeScope === null) {
496: throw new ShouldNotHappenException();
497: }
498: $templateTypeMap = new TemplateTypeMap(array_map(static fn (TemplateTag $tag): Type => TemplateTypeFactory::fromTemplateTag($templateTypeScope, $tag), $templateTags));
499: $nameScope = $nameScope->withTemplateTypeMap($templateTypeMap);
500: $templateTags = $this->phpDocNodeResolver->resolveTemplateTags($phpDocNode, $nameScope);
501: $templateTypeMap = new TemplateTypeMap(array_map(static fn (TemplateTag $tag): Type => TemplateTypeFactory::fromTemplateTag($templateTypeScope, $tag), $templateTags));
502:
503: return new TemplateTypeMap(array_merge(
504: $currentTypeMap !== null ? $currentTypeMap->getTypes() : [],
505: $templateTypeMap->getTypes(),
506: ));
507: };
508: }
509: }
510:
511: $typeMapCb = $typeMapStack[count($typeMapStack) - 1] ?? null;
512: $typeAliasesMap = $typeAliasStack[count($typeAliasStack) - 1] ?? [];
513:
514: if (
515: $node instanceof Node\Stmt
516: && !$node instanceof Node\Stmt\Namespace_
517: && !$node instanceof Node\Stmt\Declare_
518: && !$node instanceof Node\Stmt\DeclareDeclare
519: && !$node instanceof Node\Stmt\Use_
520: && !$node instanceof Node\Stmt\UseUse
521: && !$node instanceof Node\Stmt\GroupUse
522: && !$node instanceof Node\Stmt\TraitUse
523: && !$node instanceof Node\Stmt\TraitUseAdaptation
524: && !$node instanceof Node\Stmt\InlineHTML
525: && !($node instanceof Node\Stmt\Expression && $node->expr instanceof Node\Expr\Include_)
526: && !array_key_exists($nameScopeKey, $nameScopeMap)
527: ) {
528: $nameScopeMap[$nameScopeKey] = static fn (): NameScope => new NameScope(
529: $namespace,
530: $uses,
531: $className,
532: $functionName,
533: ($typeMapCb !== null ? $typeMapCb() : TemplateTypeMap::createEmpty()),
534: $typeAliasesMap,
535: false,
536: $constUses,
537: $lookForTrait,
538: );
539: }
540:
541: if ($node instanceof Node\Stmt\ClassLike || $node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Stmt\Function_) {
542: if (array_key_exists($nameScopeKey, $phpDocNodeMap)) {
543: return self::POP_TYPE_MAP_STACK;
544: }
545:
546: return null;
547: }
548:
549: if ($node instanceof Node\Stmt\Namespace_) {
550: $namespace = $node->name !== null ? (string) $node->name : null;
551: } elseif ($node instanceof Node\Stmt\Use_) {
552: if ($node->type === Node\Stmt\Use_::TYPE_NORMAL) {
553: foreach ($node->uses as $use) {
554: $uses[strtolower($use->getAlias()->name)] = (string) $use->name;
555: }
556: } elseif ($node->type === Node\Stmt\Use_::TYPE_CONSTANT) {
557: foreach ($node->uses as $use) {
558: $constUses[strtolower($use->getAlias()->name)] = (string) $use->name;
559: }
560: }
561: } elseif ($node instanceof Node\Stmt\GroupUse) {
562: $prefix = (string) $node->prefix;
563: foreach ($node->uses as $use) {
564: if ($node->type === Node\Stmt\Use_::TYPE_NORMAL || $use->type === Node\Stmt\Use_::TYPE_NORMAL) {
565: $uses[strtolower($use->getAlias()->name)] = sprintf('%s\\%s', $prefix, (string) $use->name);
566: } elseif ($node->type === Node\Stmt\Use_::TYPE_CONSTANT || $use->type === Node\Stmt\Use_::TYPE_CONSTANT) {
567: $constUses[strtolower($use->getAlias()->name)] = sprintf('%s\\%s', $prefix, (string) $use->name);
568: }
569: }
570: } elseif ($node instanceof Node\Stmt\TraitUse) {
571: $traitMethodAliases = [];
572: foreach ($node->adaptations as $traitUseAdaptation) {
573: if (!$traitUseAdaptation instanceof Node\Stmt\TraitUseAdaptation\Alias) {
574: continue;
575: }
576:
577: if ($traitUseAdaptation->newName === null) {
578: continue;
579: }
580:
581: $methodName = $traitUseAdaptation->method->toString();
582: $newTraitName = $traitUseAdaptation->newName->toString();
583:
584: if ($traitUseAdaptation->trait === null) {
585: foreach ($node->traits as $traitName) {
586: $traitMethodAliases[$traitName->toString()][$methodName] = $newTraitName;
587: }
588: continue;
589: }
590:
591: $traitMethodAliases[$traitUseAdaptation->trait->toString()][$methodName] = $newTraitName;
592: }
593:
594: $useDocComment = null;
595: if ($node->getDocComment() !== null) {
596: $useDocComment = $node->getDocComment()->getText();
597: }
598:
599: foreach ($node->traits as $traitName) {
600: /** @var class-string $traitName */
601: $traitName = (string) $traitName;
602: $reflectionProvider = $this->reflectionProviderProvider->getReflectionProvider();
603: if (!$reflectionProvider->hasClass($traitName)) {
604: continue;
605: }
606:
607: $traitReflection = $reflectionProvider->getClass($traitName);
608: if (!$traitReflection->isTrait()) {
609: continue;
610: }
611: if ($traitReflection->getFileName() === null) {
612: continue;
613: }
614: if (!is_file($traitReflection->getFileName())) {
615: continue;
616: }
617:
618: $className = $classStack[count($classStack) - 1] ?? null;
619: if ($className === null) {
620: throw new ShouldNotHappenException();
621: }
622:
623: $traitPhpDocMap = $this->createNameScopeMap(
624: $traitReflection->getFileName(),
625: $traitName,
626: $className,
627: $traitMethodAliases[$traitName] ?? [],
628: $originalClassFileName,
629: $phpDocNodeMap,
630: );
631: $finalTraitPhpDocMap = [];
632: foreach ($traitPhpDocMap as $nameScopeTraitKey => $callback) {
633: $finalTraitPhpDocMap[$nameScopeTraitKey] = function () use ($callback, $traitReflection, $fileName, $className, $lookForTrait, $useDocComment): NameScope {
634: /** @var NameScope $original */
635: $original = $callback();
636: if (!$traitReflection->isGeneric()) {
637: return $original;
638: }
639:
640: $traitTemplateTypeMap = $traitReflection->getTemplateTypeMap();
641:
642: $useType = null;
643: if ($useDocComment !== null) {
644: $useTags = $this->getResolvedPhpDoc(
645: $fileName,
646: $className,
647: $lookForTrait,
648: null,
649: $useDocComment,
650: )->getUsesTags();
651: foreach ($useTags as $useTag) {
652: $useTagType = $useTag->getType();
653: if (!$useTagType instanceof GenericObjectType) {
654: continue;
655: }
656:
657: if ($useTagType->getClassName() !== $traitReflection->getName()) {
658: continue;
659: }
660:
661: $useType = $useTagType;
662: break;
663: }
664: }
665:
666: if ($useType === null) {
667: return $original->withTemplateTypeMap($traitTemplateTypeMap->resolveToBounds());
668: }
669:
670: $transformedTraitTypeMap = $traitReflection->typeMapFromList($useType->getTypes());
671:
672: return $original->withTemplateTypeMap($traitTemplateTypeMap->map(static fn (string $name, Type $type): Type => TemplateTypeHelper::resolveTemplateTypes($type, $transformedTraitTypeMap, TemplateTypeVarianceMap::createEmpty(), TemplateTypeVariance::createStatic())));
673: };
674: }
675: $nameScopeMap = array_merge($nameScopeMap, $finalTraitPhpDocMap);
676: }
677: }
678:
679: return null;
680: },
681: static function (Node $node, $callbackResult) use (&$namespace, &$functionStack, &$classStack, &$typeAliasStack, &$uses, &$typeMapStack, &$constUses): void {
682: if ($node instanceof Node\Stmt\ClassLike) {
683: if (count($classStack) === 0) {
684: throw new ShouldNotHappenException();
685: }
686: array_pop($classStack);
687:
688: if (count($typeAliasStack) === 0) {
689: throw new ShouldNotHappenException();
690: }
691:
692: array_pop($typeAliasStack);
693:
694: if (count($functionStack) === 0) {
695: throw new ShouldNotHappenException();
696: }
697:
698: array_pop($functionStack);
699: } elseif ($node instanceof Node\Stmt\Namespace_) {
700: $namespace = null;
701: $uses = [];
702: $constUses = [];
703: } elseif ($node instanceof Node\Stmt\ClassMethod || $node instanceof Node\Stmt\Function_) {
704: if (count($functionStack) === 0) {
705: throw new ShouldNotHappenException();
706: }
707:
708: array_pop($functionStack);
709: }
710: if ($callbackResult !== self::POP_TYPE_MAP_STACK) {
711: return;
712: }
713:
714: if (count($typeMapStack) === 0) {
715: throw new ShouldNotHappenException();
716: }
717: array_pop($typeMapStack);
718: },
719: );
720:
721: if (count($typeMapStack) > 0) {
722: throw new ShouldNotHappenException();
723: }
724:
725: return $nameScopeMap;
726: }
727:
728: /**
729: * @return array<string, true>
730: */
731: private function getTypeAliasesMap(PhpDocNode $phpDocNode): array
732: {
733: $nameScope = new NameScope(null, []);
734:
735: $aliasesMap = [];
736: foreach (array_keys($this->phpDocNodeResolver->resolveTypeAliasImportTags($phpDocNode, $nameScope)) as $key) {
737: $aliasesMap[$key] = true;
738: }
739:
740: foreach (array_keys($this->phpDocNodeResolver->resolveTypeAliasTags($phpDocNode, $nameScope)) as $key) {
741: $aliasesMap[$key] = true;
742: }
743:
744: return $aliasesMap;
745: }
746:
747: /**
748: * @param Node[]|Node|scalar|null $node
749: * @param Closure(Node $node): mixed $nodeCallback
750: * @param Closure(Node $node, mixed $callbackResult): void $endNodeCallback
751: */
752: private function processNodes($node, Closure $nodeCallback, Closure $endNodeCallback): void
753: {
754: if ($node instanceof Node) {
755: $callbackResult = $nodeCallback($node);
756: if ($callbackResult === self::SKIP_NODE) {
757: return;
758: }
759: foreach ($node->getSubNodeNames() as $subNodeName) {
760: $subNode = $node->{$subNodeName};
761: $this->processNodes($subNode, $nodeCallback, $endNodeCallback);
762: }
763: $endNodeCallback($node, $callbackResult);
764: } elseif (is_array($node)) {
765: foreach ($node as $subNode) {
766: $this->processNodes($subNode, $nodeCallback, $endNodeCallback);
767: }
768: }
769: }
770:
771: private function getNameScopeKey(
772: ?string $file,
773: ?string $class,
774: ?string $trait,
775: ?string $function,
776: ): string
777: {
778: if ($class === null && $trait === null && $function === null) {
779: return md5(sprintf('%s', $file ?? 'no-file'));
780: }
781:
782: if ($class !== null && str_contains($class, 'class@anonymous')) {
783: throw new ShouldNotHappenException('Wrong anonymous class name, FilTypeMapper should be called with ClassReflection::getName().');
784: }
785:
786: return md5(sprintf('%s-%s-%s-%s', $file ?? 'no-file', $class, $trait, $function));
787: }
788:
789: }
790: