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