1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace PHPStan\BetterReflection\Reflection;
6:
7: use BackedEnum;
8: use PhpParser\Modifiers;
9: use PhpParser\Node;
10: use PhpParser\Node\Stmt\Class_ as ClassNode;
11: use PhpParser\Node\Stmt\ClassMethod;
12: use PhpParser\Node\Stmt\Enum_ as EnumNode;
13: use PhpParser\Node\Stmt\Interface_ as InterfaceNode;
14: use PhpParser\Node\Stmt\Trait_ as TraitNode;
15: use PhpParser\Node\Stmt\TraitUse;
16: use ReflectionClass as CoreReflectionClass;
17: use ReflectionException;
18: use ReflectionMethod as CoreReflectionMethod;
19: use PHPStan\BetterReflection\BetterReflection;
20: use PHPStan\BetterReflection\Reflection\Adapter\ReflectionClass as ReflectionClassAdapter;
21: use PHPStan\BetterReflection\Reflection\Adapter\ReflectionClassConstant as ReflectionClassConstantAdapter;
22: use PHPStan\BetterReflection\Reflection\Adapter\ReflectionMethod as ReflectionMethodAdapter;
23: use PHPStan\BetterReflection\Reflection\Adapter\ReflectionProperty as ReflectionPropertyAdapter;
24: use PHPStan\BetterReflection\Reflection\Attribute\ReflectionAttributeHelper;
25: use PHPStan\BetterReflection\Reflection\Deprecated\DeprecatedHelper;
26: use PHPStan\BetterReflection\Reflection\Exception\ClassDoesNotExist;
27: use PHPStan\BetterReflection\Reflection\Exception\NoObjectProvided;
28: use PHPStan\BetterReflection\Reflection\Exception\NotAnObject;
29: use PHPStan\BetterReflection\Reflection\Exception\ObjectNotInstanceOfClass;
30: use PHPStan\BetterReflection\Reflection\Exception\PropertyDoesNotExist;
31: use PHPStan\BetterReflection\Reflection\StringCast\ReflectionClassStringCast;
32: use PHPStan\BetterReflection\Reflection\Support\AlreadyVisitedClasses;
33: use PHPStan\BetterReflection\Reflector\Exception\IdentifierNotFound;
34: use PHPStan\BetterReflection\Reflector\Reflector;
35: use PHPStan\BetterReflection\SourceLocator\Located\InternalLocatedSource;
36: use PHPStan\BetterReflection\SourceLocator\Located\LocatedSource;
37: use PHPStan\BetterReflection\Util\CalculateReflectionColumn;
38: use PHPStan\BetterReflection\Util\GetLastDocComment;
39: use Stringable;
40: use Traversable;
41: use UnitEnum;
42:
43: use function array_combine;
44: use function array_filter;
45: use function array_key_exists;
46: use function array_keys;
47: use function array_map;
48: use function array_merge;
49: use function array_pop;
50: use function array_reverse;
51: use function array_slice;
52: use function array_values;
53: use function assert;
54: use function in_array;
55: use function is_int;
56: use function is_string;
57: use function ltrim;
58: use function sha1;
59: use function sprintf;
60: use function strtolower;
61:
62: /** @psalm-immutable */
63: class ReflectionClass implements Reflection
64: {
65: private Reflector $reflector;
66: private LocatedSource $locatedSource;
67: /**
68: * @var non-empty-string|null
69: */
70: private $namespace = null;
71: /**
72: * @var string
73: */
74: public const ANONYMOUS_CLASS_NAME_PREFIX = 'class@anonymous';
75: /**
76: * @var string
77: */
78: public const ANONYMOUS_CLASS_NAME_PREFIX_REGEXP = '~^(?:class|[\w\\\\]+)@anonymous~';
79: /**
80: * @var string
81: */
82: private const ANONYMOUS_CLASS_NAME_SUFFIX = '@anonymous';
83:
84: /** @var class-string|trait-string|null */
85: private $name;
86:
87: /** @var non-empty-string|null */
88: private $shortName;
89:
90: private bool $isInterface;
91: private bool $isTrait;
92: private bool $isEnum;
93: private bool $isBackedEnum;
94:
95: /** @var int-mask-of<ReflectionClassAdapter::IS_*> */
96: private int $modifiers;
97:
98: /** @var non-empty-string|null */
99: private $docComment;
100:
101: /** @var list<ReflectionAttribute> */
102: private array $attributes;
103:
104: /** @var positive-int */
105: private int $startLine;
106:
107: /** @var positive-int */
108: private int $endLine;
109:
110: /** @var positive-int */
111: private int $startColumn;
112:
113: /** @var positive-int */
114: private int $endColumn;
115:
116: /** @var class-string|null */
117: private $parentClassName;
118:
119: /** @var list<class-string> */
120: private array $implementsClassNames;
121:
122: /** @var list<trait-string> */
123: private array $traitClassNames;
124:
125: /** @var array<non-empty-string, ReflectionClassConstant> */
126: private array $immediateConstants;
127:
128: /** @var array<non-empty-string, ReflectionProperty> */
129: private array $immediateProperties;
130:
131: /** @var array<non-empty-string, ReflectionMethod> */
132: private array $immediateMethods;
133:
134: /** @var array{
135: * aliases: array<trait-string, list<array{alias: non-empty-string, method: non-empty-string, hash: non-empty-string}>>,
136: * modifiers: array<non-empty-string, int-mask-of<ReflectionMethodAdapter::IS_*>>,
137: * precedences: array<non-empty-string, non-empty-string>,
138: * hashes: array<non-empty-string, non-empty-string>,
139: * }
140: */
141: private array $traitsData;
142:
143: /**
144: * @var array<non-empty-string, ReflectionClassConstant>|null
145: * @psalm-allow-private-mutation
146: */
147: private $cachedConstants = null;
148:
149: /**
150: * @var array<non-empty-string, ReflectionProperty>|null
151: * @psalm-allow-private-mutation
152: */
153: private $cachedProperties = null;
154:
155: /** @var array<class-string, ReflectionClass>|null */
156: private $cachedInterfaces = null;
157:
158: /** @var list<class-string>|null */
159: private $cachedInterfaceNames = null;
160:
161: /** @var list<ReflectionClass>|null */
162: private $cachedTraits = null;
163:
164: /**
165: * @var \PHPStan\BetterReflection\Reflection\ReflectionMethod|null
166: */
167: private $cachedConstructor = null;
168:
169: /**
170: * @var string|null
171: */
172: private $cachedName = null;
173:
174: /**
175: * @psalm-allow-private-mutation
176: * @var array<lowercase-string, ReflectionMethod>|null
177: */
178: private $cachedMethods = null;
179:
180: /**
181: * @var list<ReflectionClass>|null
182: * @psalm-allow-private-mutation
183: */
184: private $cachedParentClasses = null;
185:
186: /** @psalm-allow-private-mutation
187: * @var bool|null */
188: private $cachedIsOnParentClassCycle = null;
189:
190: /** @psalm-allow-private-mutation
191: * @var bool|null */
192: private $cachedIsOnInterfaceCycle = null;
193:
194: /** @psalm-allow-private-mutation
195: * @var bool|null */
196: private $cachedIsOnTraitCycle = null;
197:
198: /**
199: * @internal
200: *
201: * @param non-empty-string|null $namespace
202: * @param ClassNode|InterfaceNode|TraitNode|EnumNode $node
203: */
204: protected function __construct(
205: Reflector $reflector,
206: $node,
207: LocatedSource $locatedSource,
208: ?string $namespace = null
209: ) {
210: $this->reflector = $reflector;
211: $this->locatedSource = $locatedSource;
212: $this->namespace = $namespace;
213: $name = null;
214: $shortName = null;
215:
216: if ($node->name instanceof Node\Identifier) {
217: $namespacedName = $node->namespacedName;
218: if ($namespacedName === null) {
219: /** @psalm-var class-string|trait-string */
220: $name = $node->name->name;
221: } else {
222: /** @psalm-var class-string|trait-string */
223: $name = $namespacedName->toString();
224: }
225:
226: $shortName = $node->name->name;
227: }
228:
229: $this->name = $name;
230: $this->shortName = $shortName;
231: $this->isInterface = $node instanceof InterfaceNode;
232: $this->isTrait = $node instanceof TraitNode;
233: $this->isEnum = $node instanceof EnumNode;
234: $this->isBackedEnum = $node instanceof EnumNode && $node->scalarType !== null;
235:
236: $this->modifiers = $this->computeModifiers($node);
237: $this->docComment = GetLastDocComment::forNode($node);
238: $this->attributes = ReflectionAttributeHelper::createAttributes($reflector, $this, $node->attrGroups);
239:
240: $startLine = $node->getStartLine();
241: assert($startLine > 0);
242: $endLine = $node->getEndLine();
243: assert($endLine > 0);
244:
245: $this->startLine = $startLine;
246: $this->endLine = $endLine;
247: $this->startColumn = CalculateReflectionColumn::getStartColumn($locatedSource->getSource(), $node);
248: $this->endColumn = CalculateReflectionColumn::getEndColumn($locatedSource->getSource(), $node);
249:
250: /** @var class-string|null $parentClassName */
251: $parentClassName = $node instanceof ClassNode ? ($nullsafeVariable1 = $node->extends) ? $nullsafeVariable1->toString() : null : null;
252: $this->parentClassName = $parentClassName;
253:
254: // @infection-ignore-all UnwrapArrayMap: It works without array_map() as well but this is less magical
255: /** @var list<class-string> $implementsClassNames */
256: $implementsClassNames = array_map(
257: static fn (Node\Name $name): string => $name->toString(),
258: $node instanceof TraitNode ? [] : ($node instanceof InterfaceNode ? $node->extends : $node->implements),
259: );
260: $this->implementsClassNames = $implementsClassNames;
261:
262: /** @var list<trait-string> $traitClassNames */
263: $traitClassNames = array_merge(
264: [],
265: ...array_map(
266: // @infection-ignore-all UnwrapArrayMap: It works without array_map() as well but this is less magical
267: static fn (TraitUse $traitUse): array => array_map(static fn (Node\Name $traitName): string => $traitName->toString(), $traitUse->traits),
268: $node->getTraitUses(),
269: ),
270: );
271: $this->traitClassNames = $traitClassNames;
272:
273: $this->immediateConstants = $this->createImmediateConstants($node, $reflector);
274: $this->immediateProperties = $this->createImmediateProperties($node, $reflector);
275: $this->immediateMethods = $this->createImmediateMethods($node, $reflector);
276:
277: $this->traitsData = $this->computeTraitsData($node);
278: }
279:
280: /** @return array<string, mixed> */
281: public function exportToCache(): array
282: {
283: return [
284: 'locatedSource' => $this->locatedSource->exportToCache(),
285: 'namespace' => $this->namespace,
286: 'name' => $this->name,
287: 'shortName' => $this->shortName,
288: 'isInterface' => $this->isInterface,
289: 'isTrait' => $this->isTrait,
290: 'isEnum' => $this->isEnum,
291: 'isBackedEnum' => $this->isBackedEnum,
292: 'modifiers' => $this->modifiers,
293: 'docComment' => $this->docComment,
294: 'attributes' => array_map(static fn ($ref) => $ref->exportToCache(), $this->attributes),
295: 'startLine' => $this->startLine,
296: 'endLine' => $this->endLine,
297: 'startColumn' => $this->startColumn,
298: 'endColumn' => $this->endColumn,
299: 'parentClassName' => $this->parentClassName,
300: 'implementsClassNames' => $this->implementsClassNames,
301: 'traitClassNames' => $this->traitClassNames,
302: 'immediateConstants' => array_map(static fn ($ref) => $ref->exportToCache(), $this->immediateConstants),
303: 'immediateProperties' => array_map(static fn ($ref) => $ref->exportToCache(), $this->immediateProperties),
304: // the methods share the class's located source, except the ones an enum
305: // gets from the engine (cases(), from(), tryFrom()) - their own one is
306: // derived from the class's, so it is rebuilt on import instead of exported
307: // with a second copy of the file name
308: 'immediateMethods' => array_map(
309: fn (ReflectionMethod $ref) => $ref->getLocatedSource() === $this->locatedSource
310: ? $ref->exportToCache()
311: : array_merge($ref->exportToCache(), ['isEngineProvided' => true]),
312: $this->immediateMethods,
313: ),
314: 'traitsData' => $this->traitsData,
315: ];
316: }
317:
318: /**
319: * @param array<string, mixed> $data
320: *
321: * @return static
322: */
323: public static function importFromCache(Reflector $reflector, array $data): self
324: {
325: $reflection = new CoreReflectionClass(static::class);
326: $ref = $reflection->newInstanceWithoutConstructor();
327: assert($ref instanceof static);
328: $ref->reflector = $reflector;
329:
330: $locatedSource = LocatedSource::importFromCache($data['locatedSource']);
331: $ref->locatedSource = $locatedSource;
332: $ref->namespace = $data['namespace'];
333: $ref->name = $data['name'];
334: $ref->shortName = $data['shortName'];
335: $ref->isInterface = $data['isInterface'];
336: $ref->isTrait = $data['isTrait'];
337: $ref->isEnum = $data['isEnum'];
338: $ref->isBackedEnum = $data['isBackedEnum'];
339: $ref->modifiers = $data['modifiers'];
340: $ref->docComment = $data['docComment'];
341: $ref->attributes = array_map(
342: static fn ($constData) => ReflectionAttribute::importFromCache($reflector, $constData, $ref),
343: $data['attributes'],
344: );
345: $ref->startLine = $data['startLine'];
346: $ref->endLine = $data['endLine'];
347: $ref->startColumn = $data['startColumn'];
348: $ref->endColumn = $data['endColumn'];
349: $ref->parentClassName = $data['parentClassName'];
350: $ref->implementsClassNames = $data['implementsClassNames'];
351: $ref->traitClassNames = $data['traitClassNames'];
352: $ref->immediateConstants = array_map(
353: static fn ($constData) => ReflectionClassConstant::importFromCache($reflector, $constData),
354: $data['immediateConstants'],
355: );
356: $ref->immediateProperties = array_map(
357: static fn ($propData) => ReflectionProperty::importFromCache($reflector, $propData, $locatedSource),
358: $data['immediateProperties'],
359: );
360: $ref->immediateMethods = array_map(
361: static fn ($methodData) => ReflectionMethod::importFromCache(
362: $reflector,
363: $methodData,
364: array_key_exists('isEngineProvided', $methodData) ? $ref->createEngineProvidedMethodsLocatedSource() : $locatedSource,
365: null,
366: ),
367: $data['immediateMethods'],
368: );
369: $ref->traitsData = $data['traitsData'];
370:
371: return $ref;
372: }
373:
374: /** @return non-empty-string */
375: public function __toString(): string
376: {
377: return ReflectionClassStringCast::toString($this);
378: }
379:
380: /**
381: * Create a ReflectionClass from an instance, using default reflectors etc.
382: *
383: * This is simply a helper method that calls ReflectionObject::createFromInstance().
384: *
385: * @see ReflectionObject::createFromInstance
386: *
387: * @throws IdentifierNotFound
388: * @throws ReflectionException
389: */
390: public static function createFromInstance(object $instance): self
391: {
392: return ReflectionObject::createFromInstance($instance);
393: }
394:
395: /**
396: * Create from a Class Node.
397: *
398: * @internal
399: *
400: * @param ClassNode|InterfaceNode|TraitNode|EnumNode $node Node has to be processed by the PhpParser\NodeVisitor\NameResolver
401: * @param non-empty-string|null $namespace optional - if omitted, we assume it is global namespaced class
402: */
403: public static function createFromNode(
404: Reflector $reflector,
405: $node,
406: LocatedSource $locatedSource,
407: ?string $namespace = null
408: ): self {
409: return new self($reflector, $node, $locatedSource, $namespace);
410: }
411:
412: /**
413: * Get the "short" name of the class (e.g. for A\B\Foo, this will return
414: * "Foo").
415: *
416: * @return non-empty-string
417: */
418: public function getShortName(): string
419: {
420: if ($this->shortName !== null) {
421: return $this->shortName;
422: }
423:
424: $fileName = $this->getFileName();
425:
426: if ($fileName === null) {
427: $fileName = sha1($this->locatedSource->getSource());
428: }
429:
430: return sprintf('%s%s%c%s(%d)', $this->getAnonymousClassNamePrefix(), self::ANONYMOUS_CLASS_NAME_SUFFIX, "\0", $fileName, $this->getStartLine());
431: }
432:
433: /**
434: * PHP creates the name of the anonymous class based on first parent
435: * or implemented interface.
436: */
437: private function getAnonymousClassNamePrefix(): string
438: {
439: if ($this->parentClassName !== null) {
440: return $this->parentClassName;
441: }
442:
443: $implementsClassName = $this->implementsClassNames;
444: if ($implementsClassName !== []) {
445: return $implementsClassName[0];
446: }
447:
448: return 'class';
449: }
450:
451: /**
452: * Get the "full" name of the class (e.g. for A\B\Foo, this will return
453: * "A\B\Foo").
454: *
455: * @return class-string|trait-string
456: */
457: public function getName(): string
458: {
459: if ($this->cachedName !== null) {
460: return $this->cachedName;
461: }
462:
463: if (! $this->inNamespace()) {
464: /** @psalm-var class-string|trait-string */
465: return $this->cachedName = $this->getShortName();
466: }
467:
468: assert($this->name !== null);
469:
470: return $this->cachedName = $this->name;
471: }
472:
473: /** @return class-string|null */
474: public function getParentClassName(): ?string
475: {
476: return $this->parentClassName;
477: }
478:
479: /**
480: * Get the "namespace" name of the class (e.g. for A\B\Foo, this will
481: * return "A\B").
482: *
483: * @return non-empty-string|null
484: */
485: public function getNamespaceName(): ?string
486: {
487: return $this->namespace;
488: }
489:
490: /**
491: * Decide if this class is part of a namespace. Returns false if the class
492: * is in the global namespace or does not have a specified namespace.
493: */
494: public function inNamespace(): bool
495: {
496: return $this->namespace !== null;
497: }
498:
499: /** @return non-empty-string|null */
500: public function getExtensionName(): ?string
501: {
502: return $this->locatedSource->getExtensionName();
503: }
504:
505: /**
506: * @param array<lowercase-string, ReflectionMethod> $currentMethods
507: *
508: * @return list<ReflectionMethod>
509: */
510: private function createMethodsFromTrait(ReflectionMethod $method, array $currentMethods): array
511: {
512: $methodModifiers = $method->getModifiers();
513: $lowerCasedMethodHash = $this->lowerCasedMethodHash($method->getImplementingClass()->getName(), $method->getName());
514:
515: if (array_key_exists($lowerCasedMethodHash, $this->traitsData['modifiers'])) {
516: $newModifierAst = $this->traitsData['modifiers'][$lowerCasedMethodHash];
517: if ($this->traitsData['modifiers'][$lowerCasedMethodHash] & ClassNode::VISIBILITY_MODIFIER_MASK) {
518: $methodModifiersWithoutVisibility = $methodModifiers;
519: if (($methodModifiers & CoreReflectionMethod::IS_PUBLIC) === CoreReflectionMethod::IS_PUBLIC) {
520: $methodModifiersWithoutVisibility -= CoreReflectionMethod::IS_PUBLIC;
521: }
522:
523: if (($methodModifiers & CoreReflectionMethod::IS_PROTECTED) === CoreReflectionMethod::IS_PROTECTED) {
524: $methodModifiersWithoutVisibility -= CoreReflectionMethod::IS_PROTECTED;
525: }
526:
527: if (($methodModifiers & CoreReflectionMethod::IS_PRIVATE) === CoreReflectionMethod::IS_PRIVATE) {
528: $methodModifiersWithoutVisibility -= CoreReflectionMethod::IS_PRIVATE;
529: }
530:
531: $newModifier = 0;
532: if (($newModifierAst & Modifiers::PUBLIC) === Modifiers::PUBLIC) {
533: $newModifier = CoreReflectionMethod::IS_PUBLIC;
534: }
535:
536: if (($newModifierAst & Modifiers::PROTECTED) === Modifiers::PROTECTED) {
537: $newModifier = CoreReflectionMethod::IS_PROTECTED;
538: }
539:
540: if (($newModifierAst & Modifiers::PRIVATE) === Modifiers::PRIVATE) {
541: $newModifier = CoreReflectionMethod::IS_PRIVATE;
542: }
543:
544: $methodModifiers = $methodModifiersWithoutVisibility | $newModifier;
545: }
546:
547: if (($newModifierAst & Modifiers::FINAL) === Modifiers::FINAL) {
548: $methodModifiers |= CoreReflectionMethod::IS_FINAL;
549: }
550: }
551:
552: $createMethod = function (?string $aliasMethodName, int $methodModifiers) use ($method): ReflectionMethod {
553: assert($aliasMethodName === null || $aliasMethodName !== '');
554:
555: /** @var int-mask-of<ReflectionMethodAdapter::IS_*> $methodModifiers */
556: $methodModifiers = $methodModifiers;
557:
558: return $method->withImplementingClass($this, $aliasMethodName, $methodModifiers);
559: };
560:
561: $methods = [];
562:
563: if (
564: ! array_key_exists($lowerCasedMethodHash, $this->traitsData['precedences'])
565: && ! array_key_exists($lowerCasedMethodHash, $currentMethods)
566: ) {
567: $modifiersUsedWithAlias = false;
568:
569: foreach ($this->traitsData['aliases'] as $traitAliasDefinitions) {
570: foreach ($traitAliasDefinitions as $traitAliasDefinition) {
571: if ($lowerCasedMethodHash === $traitAliasDefinition['hash']) {
572: $modifiersUsedWithAlias = true;
573: break;
574: }
575: }
576: }
577:
578: // Modifiers used with alias -> copy method with original modifiers (will be added later with the alias name and new modifiers)
579: // Modifiers not used with alias -> add method with new modifiers
580: $methods[] = $createMethod($method->getAliasName(), $modifiersUsedWithAlias ? $method->getModifiers() : $methodModifiers);
581: }
582:
583: if ($this->traitsData['aliases'] !== []) {
584: $traits = [];
585: foreach ($this->getTraits() as $trait) {
586: $traits[$trait->getName()] = $trait;
587: }
588:
589: foreach ($this->traitsData['aliases'] as $traitClassName => $traitAliasDefinitions) {
590: foreach ($traitAliasDefinitions as $traitAliasDefinition) {
591: if ($lowerCasedMethodHash !== $traitAliasDefinition['hash']) {
592: continue;
593: }
594:
595: if (! array_key_exists($traitClassName, $traits)) {
596: continue;
597: }
598:
599: if (! $traits[$traitClassName]->hasMethod($traitAliasDefinition['method'])) {
600: continue;
601: }
602:
603: $methods[] = $createMethod($traitAliasDefinition['alias'], $methodModifiers);
604: }
605: }
606: }
607:
608: return $methods;
609: }
610:
611: /**
612: * Construct a flat list of all methods in this precise order from:
613: * - current class
614: * - parent class
615: * - traits used in parent class
616: * - interfaces implemented in parent class
617: * - traits used in current class
618: * - interfaces implemented in current class
619: *
620: * Methods are not merged via their name as array index, since internal PHP method
621: * sorting does not follow `\array_merge()` semantics.
622: *
623: * @return array<lowercase-string, ReflectionMethod> indexed by method name
624: */
625: private function getMethodsIndexedByLowercasedName(AlreadyVisitedClasses $alreadyVisitedClasses): array
626: {
627: if ($this->cachedMethods !== null) {
628: return $this->cachedMethods;
629: }
630:
631: $alreadyVisitedClasses->push($this->getName());
632:
633: $immediateMethods = $this->getImmediateMethods();
634: $className = $this->getName();
635:
636: $methods = array_combine(
637: array_map(static fn (ReflectionMethod $method): string => strtolower($method->getName()), $immediateMethods),
638: $immediateMethods,
639: );
640:
641: $parentClass = $this->getParentClass();
642: if ($parentClass !== null) {
643: foreach ($parentClass->getMethodsIndexedByLowercasedName($alreadyVisitedClasses) as $lowercasedMethodName => $method) {
644: if (array_key_exists($lowercasedMethodName, $methods)) {
645: continue;
646: }
647:
648: $methods[$lowercasedMethodName] = $method->withCurrentClass($this);
649: }
650: }
651:
652: foreach ($this->getTraits() as $trait) {
653: $alreadyVisitedClassesCopy = clone $alreadyVisitedClasses;
654: foreach ($trait->getMethodsIndexedByLowercasedName($alreadyVisitedClassesCopy) as $method) {
655: foreach ($this->createMethodsFromTrait($method, $methods) as $traitMethod) {
656: $lowercasedMethodName = strtolower($traitMethod->getName());
657:
658: if (! array_key_exists($lowercasedMethodName, $methods)) {
659: $methods[$lowercasedMethodName] = $traitMethod;
660: continue;
661: }
662:
663: if ($traitMethod->isAbstract()) {
664: continue;
665: }
666:
667: // Non-abstract trait method can overwrite existing method:
668: // - when existing method comes from parent class
669: // - when existing method comes from trait and is abstract
670:
671: $existingMethod = $methods[$lowercasedMethodName];
672:
673: if (
674: $existingMethod->getDeclaringClass()->getName() === $className
675: && ! (
676: $existingMethod->isAbstract()
677: && $existingMethod->getDeclaringClass()->isTrait()
678: )
679: ) {
680: continue;
681: }
682:
683: $methods[$lowercasedMethodName] = $traitMethod;
684: }
685: }
686: }
687:
688: foreach ($this->getImmediateInterfaces() as $interface) {
689: $alreadyVisitedClassesCopy = clone $alreadyVisitedClasses;
690: foreach ($interface->getMethodsIndexedByLowercasedName($alreadyVisitedClassesCopy) as $lowercasedMethodName => $method) {
691: if (array_key_exists($lowercasedMethodName, $methods)) {
692: continue;
693: }
694:
695: $methods[$lowercasedMethodName] = $method;
696: }
697: }
698:
699: $this->cachedMethods = $methods;
700:
701: return $this->cachedMethods;
702: }
703:
704: /**
705: * Fetch an array of all methods for this class.
706: *
707: * Filter the results to include only methods with certain attributes. Defaults
708: * to no filtering.
709: * Any combination of \ReflectionMethod::IS_STATIC,
710: * \ReflectionMethod::IS_PUBLIC,
711: * \ReflectionMethod::IS_PROTECTED,
712: * \ReflectionMethod::IS_PRIVATE,
713: * \ReflectionMethod::IS_ABSTRACT,
714: * \ReflectionMethod::IS_FINAL.
715: * For example if $filter = \ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_FINAL
716: * the only the final public methods will be returned
717: *
718: * @param int-mask-of<CoreReflectionMethod::IS_*> $filter
719: *
720: * @return array<non-empty-string, ReflectionMethod>
721: */
722: public function getMethods(int $filter = 0): array
723: {
724: $methods = $this->cachedMethods ?? $this->getMethodsIndexedByLowercasedName(AlreadyVisitedClasses::createEmpty());
725:
726: if ($filter !== 0) {
727: $methods = array_filter(
728: $methods,
729: static fn (ReflectionMethod $method): bool => (bool) ($filter & $method->getModifiers()),
730: );
731: }
732:
733: return array_combine(
734: array_map(static fn (ReflectionMethod $method): string => $method->getName(), $methods),
735: $methods,
736: );
737: }
738:
739: /**
740: * Get only the methods that this class implements (i.e. do not search
741: * up parent classes etc.)
742: *
743: * @see ReflectionClass::getMethods for the usage of $filter
744: *
745: * @param int-mask-of<CoreReflectionMethod::IS_*> $filter
746: *
747: * @return array<non-empty-string, ReflectionMethod>
748: */
749: public function getImmediateMethods(int $filter = 0): array
750: {
751: if ($filter === 0) {
752: return $this->immediateMethods;
753: }
754:
755: return array_filter(
756: $this->immediateMethods,
757: static fn (ReflectionMethod $method): bool => (bool) ($filter & $method->getModifiers()),
758: );
759: }
760:
761: /** @return array<non-empty-string, ReflectionMethod>
762: * @param ClassNode|InterfaceNode|TraitNode|EnumNode $node */
763: private function createImmediateMethods($node, Reflector $reflector): array
764: {
765: $methods = [];
766:
767: foreach ($node->getMethods() as $methodNode) {
768: $method = ReflectionMethod::createFromMethodNode(
769: $reflector,
770: $methodNode,
771: $this->locatedSource,
772: $this->getNamespaceName(),
773: $this,
774: $this,
775: $this,
776: );
777:
778: if (array_key_exists($method->getName(), $methods)) {
779: continue;
780: }
781:
782: $methods[$method->getName()] = $method;
783: }
784:
785: if ($node instanceof EnumNode) {
786: $methods = $this->addEnumMethods($node, $methods);
787: }
788:
789: return $methods;
790: }
791:
792: /** The located source of the methods an enum gets from the engine: cases(), from() and tryFrom(). */
793: private function createEngineProvidedMethodsLocatedSource(): InternalLocatedSource
794: {
795: return new InternalLocatedSource('', $this->getName(), 'Core', $this->getFileName());
796: }
797:
798: /**
799: * @param array<non-empty-string, ReflectionMethod> $methods
800: *
801: * @return array<non-empty-string, ReflectionMethod>
802: */
803: private function addEnumMethods(EnumNode $node, array $methods): array
804: {
805: $internalLocatedSource = $this->createEngineProvidedMethodsLocatedSource();
806: $createMethod = function (string $name, array $params, $returnType) use ($internalLocatedSource): ReflectionMethod {
807: assert($name !== '');
808:
809: /** @var array{flags: int, params: Node\Param[], returnType: Node\Identifier|Node\NullableType} $classMethodSubnodes */
810: $classMethodSubnodes = [
811: 'flags' => Modifiers::PUBLIC | Modifiers::STATIC,
812: 'params' => $params,
813: 'returnType' => $returnType,
814: ];
815:
816: return ReflectionMethod::createFromMethodNode(
817: $this->reflector,
818: new ClassMethod(
819: new Node\Identifier($name),
820: $classMethodSubnodes,
821: ),
822: $internalLocatedSource,
823: $this->getNamespaceName(),
824: $this,
825: $this,
826: $this,
827: );
828: };
829:
830: $methods['cases'] = $createMethod('cases', [], new Node\Identifier('array'));
831:
832: if ($node->scalarType === null) {
833: return $methods;
834: }
835:
836: $valueParameter = new Node\Param(
837: new Node\Expr\Variable('value'),
838: null,
839: new Node\UnionType([new Node\Identifier('string'), new Node\Identifier('int')]),
840: );
841:
842: $methods['from'] = $createMethod(
843: 'from',
844: [$valueParameter],
845: new Node\Identifier('static'),
846: );
847:
848: $methods['tryFrom'] = $createMethod(
849: 'tryFrom',
850: [$valueParameter],
851: new Node\NullableType(new Node\Identifier('static')),
852: );
853:
854: return $methods;
855: }
856:
857: /**
858: * Get a single method with the name $methodName.
859: *
860: * @param non-empty-string $methodName
861: */
862: public function getMethod(string $methodName): ?\PHPStan\BetterReflection\Reflection\ReflectionMethod
863: {
864: $methods = $this->cachedMethods ?? $this->getMethodsIndexedByLowercasedName(AlreadyVisitedClasses::createEmpty());
865:
866: return $methods[strtolower($methodName)] ?? null;
867: }
868:
869: /**
870: * Does the class have the specified method?
871: *
872: * @param non-empty-string $methodName
873: */
874: public function hasMethod(string $methodName): bool
875: {
876: return $this->getMethod($methodName) !== null;
877: }
878:
879: /**
880: * Get an associative array of only the constants for this specific class (i.e. do not search
881: * up parent classes etc.), with keys as constant names and values as {@see ReflectionClassConstant} objects.
882: *
883: * @param int-mask-of<ReflectionClassConstantAdapter::IS_*> $filter
884: *
885: * @return array<non-empty-string, ReflectionClassConstant> indexed by name
886: */
887: public function getImmediateConstants(int $filter = 0): array
888: {
889: if ($filter === 0) {
890: return $this->immediateConstants;
891: }
892:
893: return array_filter(
894: $this->immediateConstants,
895: static fn (ReflectionClassConstant $constant): bool => (bool) ($filter & $constant->getModifiers()),
896: );
897: }
898:
899: /**
900: * Does this class have the specified constant?
901: *
902: * @param non-empty-string $name
903: */
904: public function hasConstant(string $name): bool
905: {
906: return $this->getConstant($name) !== null;
907: }
908:
909: /**
910: * Get the reflection object of the specified class constant.
911: *
912: * Returns null if not specified.
913: *
914: * @param non-empty-string $name
915: */
916: public function getConstant(string $name): ?\PHPStan\BetterReflection\Reflection\ReflectionClassConstant
917: {
918: return $this->getConstants()[$name] ?? null;
919: }
920:
921: /** @return array<non-empty-string, ReflectionClassConstant>
922: * @param ClassNode|InterfaceNode|TraitNode|EnumNode $node */
923: private function createImmediateConstants($node, Reflector $reflector): array
924: {
925: $constants = [];
926:
927: foreach ($node->getConstants() as $constantsNode) {
928: foreach (array_keys($constantsNode->consts) as $constantPositionInNode) {
929: assert(is_int($constantPositionInNode));
930: $constant = ReflectionClassConstant::createFromNode($reflector, $constantsNode, $constantPositionInNode, $this, $this);
931:
932: $constants[$constant->getName()] = $constant;
933: }
934: }
935:
936: return $constants;
937: }
938:
939: /**
940: * Get an associative array of the defined constants in this class,
941: * with keys as constant names and values as {@see ReflectionClassConstant} objects.
942: *
943: * @param int-mask-of<ReflectionClassConstantAdapter::IS_*> $filter
944: *
945: * @return array<non-empty-string, ReflectionClassConstant> indexed by name
946: */
947: public function getConstants(int $filter = 0): array
948: {
949: $constants = $this->cachedConstants ?? $this->getConstantsConsideringAlreadyVisitedClasses(AlreadyVisitedClasses::createEmpty());
950:
951: if ($filter === 0) {
952: return $constants;
953: }
954:
955: return array_filter(
956: $constants,
957: static fn (ReflectionClassConstant $constant): bool => (bool) ($filter & $constant->getModifiers()),
958: );
959: }
960:
961: /** @return array<non-empty-string, ReflectionClassConstant> indexed by name */
962: private function getConstantsConsideringAlreadyVisitedClasses(AlreadyVisitedClasses $alreadyVisitedClasses): array
963: {
964: if ($this->cachedConstants !== null) {
965: return $this->cachedConstants;
966: }
967:
968: $alreadyVisitedClasses->push($this->getName());
969:
970: // Note: constants are not merged via their name as array index, since internal PHP constant
971: // sorting does not follow `\array_merge()` semantics
972:
973: $constants = $this->getImmediateConstants();
974:
975: $parentClass = $this->getParentClass();
976: if ($parentClass !== null) {
977: foreach ($parentClass->getConstantsConsideringAlreadyVisitedClasses($alreadyVisitedClasses) as $constantName => $constant) {
978: if ($constant->isPrivate()) {
979: continue;
980: }
981:
982: if (array_key_exists($constantName, $constants)) {
983: continue;
984: }
985:
986: $constants[$constantName] = $constant;
987: }
988: }
989:
990: foreach ($this->getTraits() as $trait) {
991: foreach ($trait->getConstantsConsideringAlreadyVisitedClasses($alreadyVisitedClasses) as $constantName => $constant) {
992: if (array_key_exists($constantName, $constants)) {
993: continue;
994: }
995:
996: $constants[$constantName] = $constant->withImplementingClass($this);
997: }
998: }
999:
1000: foreach ($this->getImmediateInterfaces() as $interface) {
1001: $alreadyVisitedClassesCopy = clone $alreadyVisitedClasses;
1002: foreach ($interface->getConstantsConsideringAlreadyVisitedClasses($alreadyVisitedClassesCopy) as $constantName => $constant) {
1003: if (array_key_exists($constantName, $constants)) {
1004: continue;
1005: }
1006:
1007: $constants[$constantName] = $constant;
1008: }
1009: }
1010:
1011: $this->cachedConstants = $constants;
1012:
1013: return $this->cachedConstants;
1014: }
1015:
1016: /**
1017: * Get the constructor method for this class.
1018: */
1019: public function getConstructor(): ?\PHPStan\BetterReflection\Reflection\ReflectionMethod
1020: {
1021: if ($this->cachedConstructor !== null) {
1022: return $this->cachedConstructor;
1023: }
1024:
1025: $constructors = array_values(array_filter($this->getMethods(), static fn (ReflectionMethod $method): bool => $method->isConstructor()));
1026:
1027: return $this->cachedConstructor = $constructors[0] ?? null;
1028: }
1029:
1030: /**
1031: * Get only the properties for this specific class (i.e. do not search
1032: * up parent classes etc.)
1033: *
1034: * @see ReflectionClass::getProperties() for the usage of filter
1035: *
1036: * @param int-mask-of<ReflectionPropertyAdapter::IS_*> $filter
1037: *
1038: * @return array<non-empty-string, ReflectionProperty>
1039: */
1040: public function getImmediateProperties(int $filter = 0): array
1041: {
1042: if ($filter === 0) {
1043: return $this->immediateProperties;
1044: }
1045:
1046: return array_filter(
1047: $this->immediateProperties,
1048: static fn (ReflectionProperty $property): bool => (bool) ($filter & $property->getModifiers()),
1049: );
1050: }
1051:
1052: /** @return array<non-empty-string, ReflectionProperty>
1053: * @param ClassNode|InterfaceNode|TraitNode|EnumNode $node */
1054: private function createImmediateProperties($node, Reflector $reflector): array
1055: {
1056: $properties = [];
1057:
1058: foreach ($node->getProperties() as $propertiesNode) {
1059: foreach ($propertiesNode->props as $propertyPropertyNode) {
1060: $property = ReflectionProperty::createFromNode(
1061: $reflector,
1062: $propertiesNode,
1063: $propertyPropertyNode,
1064: $this,
1065: $this,
1066: );
1067: $properties[$property->getName()] = $property;
1068: }
1069: }
1070:
1071: foreach ($node->getMethods() as $methodNode) {
1072: if ($methodNode->name->toLowerString() !== '__construct') {
1073: continue;
1074: }
1075:
1076: foreach ($methodNode->params as $parameterNode) {
1077: if ($parameterNode->flags === 0 && $parameterNode->hooks === []) {
1078: // No flags, no promotion
1079: continue;
1080: }
1081:
1082: $parameterNameNode = $parameterNode->var;
1083: assert($parameterNameNode instanceof Node\Expr\Variable);
1084: assert(is_string($parameterNameNode->name));
1085:
1086: $propertyNode = new Node\Stmt\Property(
1087: $parameterNode->flags,
1088: [new Node\PropertyItem($parameterNameNode->name, $parameterNode->default)],
1089: $parameterNode->getAttributes(),
1090: $parameterNode->type,
1091: $parameterNode->attrGroups,
1092: $parameterNode->hooks,
1093: );
1094: $property = ReflectionProperty::createFromNode(
1095: $reflector,
1096: $propertyNode,
1097: $propertyNode->props[0],
1098: $this,
1099: $this,
1100: true,
1101: );
1102: $properties[$property->getName()] = $property;
1103: }
1104: }
1105:
1106: if ($node instanceof EnumNode || $node instanceof InterfaceNode) {
1107: $properties = $this->addEnumProperties($properties, $node, $reflector);
1108: }
1109:
1110: return $properties;
1111: }
1112:
1113: /**
1114: * @param array<non-empty-string, ReflectionProperty> $properties
1115: *
1116: * @return array<non-empty-string, ReflectionProperty>
1117: * @param EnumNode|InterfaceNode $node
1118: */
1119: private function addEnumProperties(array $properties, $node, Reflector $reflector): array
1120: {
1121: $createProperty = function (string $name, $type) use ($reflector): ReflectionProperty {
1122: $propertyNode = new Node\Stmt\Property(
1123: Modifiers::PUBLIC | Modifiers::READONLY,
1124: [new Node\PropertyItem($name)],
1125: [],
1126: $type,
1127: );
1128:
1129: return ReflectionProperty::createFromNode(
1130: $reflector,
1131: $propertyNode,
1132: $propertyNode->props[0],
1133: $this,
1134: $this,
1135: );
1136: };
1137:
1138: if ($node instanceof InterfaceNode) {
1139: $interfaceName = $this->getName();
1140: if ($interfaceName === 'UnitEnum') {
1141: $properties['name'] = $createProperty('name', new Node\Identifier('string'));
1142: }
1143:
1144: if ($interfaceName === 'BackedEnum') {
1145: $properties['value'] = $createProperty('value', new Node\UnionType([
1146: new Node\Identifier('int'),
1147: new Node\Identifier('string'),
1148: ]));
1149: }
1150: } else {
1151: $properties['name'] = $createProperty('name', new Node\Identifier('string'));
1152:
1153: if ($node->scalarType !== null) {
1154: $properties['value'] = $createProperty('value', $node->scalarType);
1155: }
1156: }
1157:
1158: return $properties;
1159: }
1160:
1161: /**
1162: * Get the properties for this class.
1163: *
1164: * Filter the results to include only properties with certain attributes. Defaults
1165: * to no filtering.
1166: * Any combination of \ReflectionProperty::IS_STATIC,
1167: * \ReflectionProperty::IS_PUBLIC,
1168: * \ReflectionProperty::IS_PROTECTED,
1169: * \ReflectionProperty::IS_PRIVATE.
1170: * For example if $filter = \ReflectionProperty::IS_STATIC | \ReflectionProperty::IS_PUBLIC
1171: * only the static public properties will be returned
1172: *
1173: * @param int-mask-of<ReflectionPropertyAdapter::IS_*> $filter
1174: *
1175: * @return array<non-empty-string, ReflectionProperty>
1176: */
1177: public function getProperties(int $filter = 0): array
1178: {
1179: $properties = $this->cachedProperties ?? $this->getPropertiesConsideringAlreadyVisitedClasses(AlreadyVisitedClasses::createEmpty());
1180:
1181: if ($filter === 0) {
1182: return $properties;
1183: }
1184:
1185: return array_filter(
1186: $properties,
1187: static fn (ReflectionProperty $property): bool => (bool) ($filter & $property->getModifiers()),
1188: );
1189: }
1190:
1191: /** @return array<non-empty-string, ReflectionProperty> */
1192: private function getPropertiesConsideringAlreadyVisitedClasses(AlreadyVisitedClasses $alreadyVisitedClasses): array
1193: {
1194: if ($this->cachedProperties !== null) {
1195: return $this->cachedProperties;
1196: }
1197:
1198: $alreadyVisitedClasses->push($this->getName());
1199:
1200: $immediateProperties = $this->getImmediateProperties();
1201:
1202: // Merging together properties from parent class, interfaces, traits, current class (in this precise order)
1203:
1204: $properties = array_merge(
1205: array_filter(
1206: (($nullsafeVariable2 = $this->getParentClass()) ? $nullsafeVariable2->getPropertiesConsideringAlreadyVisitedClasses($alreadyVisitedClasses) : null) ?? [],
1207: static fn (ReflectionProperty $property) => ! $property->isPrivate(),
1208: ),
1209: ...array_map(
1210: static fn (ReflectionClass $ancestor): array => $ancestor->getPropertiesConsideringAlreadyVisitedClasses(clone $alreadyVisitedClasses),
1211: array_values($this->getImmediateInterfaces()),
1212: ),
1213: );
1214:
1215: foreach ($this->getTraits() as $trait) {
1216: foreach ($trait->getPropertiesConsideringAlreadyVisitedClasses($alreadyVisitedClasses) as $traitProperty) {
1217: $traitPropertyName = $traitProperty->getName();
1218:
1219: $existingProperty = $immediateProperties[$traitPropertyName] ?? $properties[$traitPropertyName] ?? null;
1220:
1221: if ($existingProperty !== null && ! $existingProperty->isAbstract()) {
1222: continue;
1223: }
1224:
1225: $properties[$traitPropertyName] = $traitProperty->withImplementingClass($this);
1226: }
1227: }
1228:
1229: // Merge immediate properties last to get the required order
1230: $properties = array_merge($properties, $immediateProperties);
1231:
1232: $this->cachedProperties = $properties;
1233:
1234: return $this->cachedProperties;
1235: }
1236:
1237: /**
1238: * Get the property called $name.
1239: *
1240: * Returns null if property does not exist.
1241: *
1242: * @param non-empty-string $name
1243: */
1244: public function getProperty(string $name): ?\PHPStan\BetterReflection\Reflection\ReflectionProperty
1245: {
1246: $properties = $this->getProperties();
1247:
1248: if (! isset($properties[$name])) {
1249: return null;
1250: }
1251:
1252: return $properties[$name];
1253: }
1254:
1255: /**
1256: * Does this class have the specified property?
1257: *
1258: * @param non-empty-string $name
1259: */
1260: public function hasProperty(string $name): bool
1261: {
1262: return $this->getProperty($name) !== null;
1263: }
1264:
1265: /** @return array<non-empty-string, mixed> */
1266: public function getDefaultProperties(): array
1267: {
1268: return array_map(
1269: static fn (ReflectionProperty $property) => $property->getDefaultValue(),
1270: $this->getProperties(),
1271: );
1272: }
1273:
1274: /** @return non-empty-string|null */
1275: public function getFileName(): ?string
1276: {
1277: return $this->locatedSource->getFileName();
1278: }
1279:
1280: public function getLocatedSource(): LocatedSource
1281: {
1282: return $this->locatedSource;
1283: }
1284:
1285: /**
1286: * Get the line number that this class starts on.
1287: *
1288: * @return positive-int
1289: */
1290: public function getStartLine(): int
1291: {
1292: return $this->startLine;
1293: }
1294:
1295: /**
1296: * Get the line number that this class ends on.
1297: *
1298: * @return positive-int
1299: */
1300: public function getEndLine(): int
1301: {
1302: return $this->endLine;
1303: }
1304:
1305: /** @return positive-int */
1306: public function getStartColumn(): int
1307: {
1308: return $this->startColumn;
1309: }
1310:
1311: /** @return positive-int */
1312: public function getEndColumn(): int
1313: {
1314: return $this->endColumn;
1315: }
1316:
1317: /**
1318: * Get the parent class, if it is defined.
1319: */
1320: public function getParentClass(): ?\PHPStan\BetterReflection\Reflection\ReflectionClass
1321: {
1322: $parentClassName = $this->getParentClassName();
1323: if ($parentClassName === null) {
1324: return null;
1325: }
1326:
1327: if ($this->isOnParentClassCycle()) {
1328: return null;
1329: }
1330:
1331: try {
1332: return $this->reflector->reflectClass($parentClassName);
1333: } catch (IdentifierNotFound $exception) {
1334: return null;
1335: }
1336: }
1337:
1338: /**
1339: * Whether the class extends itself, directly or through other classes. PHP cannot declare such
1340: * a class, so it has no parent here, and every walk up the class hierarchy ends.
1341: */
1342: private function isOnParentClassCycle(): bool
1343: {
1344: return $this->cachedIsOnParentClassCycle ??= $this->reachesItself(
1345: static fn (self $class): array => $class->parentClassName === null ? [] : [$class->parentClassName],
1346: );
1347: }
1348:
1349: /**
1350: * Whether the interface extends itself, directly or through other interfaces. PHP cannot declare
1351: * such an interface, so it extends no interface here, and every walk over the hierarchy ends.
1352: */
1353: private function isOnInterfaceCycle(): bool
1354: {
1355: return $this->cachedIsOnInterfaceCycle ??= $this->reachesItself(
1356: static fn (self $class): array => $class->isInterface ? $class->implementsClassNames : [],
1357: );
1358: }
1359:
1360: /**
1361: * Whether the trait uses itself, directly or through other traits. PHP cannot declare such
1362: * a trait, so it uses no trait here, and every walk over the used traits ends.
1363: */
1364: private function isOnTraitCycle(): bool
1365: {
1366: return $this->cachedIsOnTraitCycle ??= $this->reachesItself(
1367: static fn (self $class): array => $class->isTrait ? $class->traitClassNames : [],
1368: );
1369: }
1370:
1371: /**
1372: * Follows the declared names, not the reflected classes, so that the answer depends only on
1373: * the declarations and not on which class is reflected first.
1374: *
1375: * @param callable(self): list<class-string> $edges
1376: */
1377: private function reachesItself(callable $edges): bool
1378: {
1379: $lowercasedName = strtolower($this->getName());
1380: $visited = [];
1381: $stack = $edges($this);
1382:
1383: while ($stack !== []) {
1384: $className = array_pop($stack);
1385: $lowercasedClassName = strtolower($className);
1386: if ($lowercasedClassName === $lowercasedName) {
1387: return true;
1388: }
1389:
1390: if (array_key_exists($lowercasedClassName, $visited)) {
1391: continue;
1392: }
1393:
1394: $visited[$lowercasedClassName] = true;
1395:
1396: try {
1397: $class = $this->reflector->reflectClass($className);
1398: } catch (IdentifierNotFound $exception) {
1399: continue;
1400: }
1401:
1402: foreach ($edges($class) as $nextClassName) {
1403: $stack[] = $nextClassName;
1404: }
1405: }
1406:
1407: return false;
1408: }
1409:
1410: /**
1411: * Gets the parent class names.
1412: *
1413: * @return list<class-string> A numerical array with parent class names as the values.
1414: */
1415: public function getParentClassNames(): array
1416: {
1417: return array_map(static fn (self $parentClass): string => $parentClass->getName(), $this->getParentClasses());
1418: }
1419:
1420: /** @return list<ReflectionClass> */
1421: private function getParentClasses(): array
1422: {
1423: if ($this->cachedParentClasses === null) {
1424: $parentClasses = [];
1425:
1426: // a class on a parent class cycle has no parent, so the chain always ends
1427: $class = $this;
1428: while (($parentClass = $class->getParentClass()) !== null) {
1429: $parentClasses[] = $parentClass;
1430: $class = $parentClass;
1431: }
1432:
1433: $this->cachedParentClasses = $parentClasses;
1434: }
1435:
1436: return $this->cachedParentClasses;
1437: }
1438:
1439: /** @return non-empty-string|null */
1440: public function getDocComment(): ?string
1441: {
1442: return $this->docComment;
1443: }
1444:
1445: public function isAnonymous(): bool
1446: {
1447: return $this->name === null;
1448: }
1449:
1450: /**
1451: * Is this an internal class?
1452: */
1453: public function isInternal(): bool
1454: {
1455: return $this->locatedSource->isInternal();
1456: }
1457:
1458: /**
1459: * Is this a user-defined function (will always return the opposite of
1460: * whatever isInternal returns).
1461: */
1462: public function isUserDefined(): bool
1463: {
1464: return ! $this->isInternal();
1465: }
1466:
1467: public function isDeprecated(): bool
1468: {
1469: return DeprecatedHelper::isDeprecated($this);
1470: }
1471:
1472: /**
1473: * Is this class an abstract class.
1474: */
1475: public function isAbstract(): bool
1476: {
1477: return (bool) ($this->modifiers & CoreReflectionClass::IS_EXPLICIT_ABSTRACT);
1478: }
1479:
1480: /**
1481: * Is this class a final class.
1482: */
1483: public function isFinal(): bool
1484: {
1485: if ($this->isEnum) {
1486: return true;
1487: }
1488:
1489: return (bool) ($this->modifiers & CoreReflectionClass::IS_FINAL);
1490: }
1491:
1492: public function isReadOnly(): bool
1493: {
1494: return (bool) ($this->modifiers & ReflectionClassAdapter::IS_READONLY_COMPATIBILITY);
1495: }
1496:
1497: /**
1498: * Get the core-reflection-compatible modifier values.
1499: *
1500: * @return int-mask-of<ReflectionClassAdapter::IS_*>
1501: */
1502: public function getModifiers(): int
1503: {
1504: return $this->modifiers;
1505: }
1506:
1507: /** @return int-mask-of<ReflectionClassAdapter::IS_*>
1508: * @param ClassNode|InterfaceNode|TraitNode|EnumNode $node */
1509: private function computeModifiers($node): int
1510: {
1511: if (! $node instanceof ClassNode) {
1512: return 0;
1513: }
1514:
1515: $modifiers = $node->isAbstract() ? CoreReflectionClass::IS_EXPLICIT_ABSTRACT : 0;
1516: $modifiers += $node->isFinal() ? CoreReflectionClass::IS_FINAL : 0;
1517: $modifiers += $node->isReadonly() ? ReflectionClassAdapter::IS_READONLY_COMPATIBILITY : 0;
1518:
1519: return $modifiers;
1520: }
1521:
1522: /**
1523: * Is this reflection a trait?
1524: */
1525: public function isTrait(): bool
1526: {
1527: return $this->isTrait;
1528: }
1529:
1530: /**
1531: * Is this reflection an interface?
1532: */
1533: public function isInterface(): bool
1534: {
1535: return $this->isInterface;
1536: }
1537:
1538: /**
1539: * Get the traits used, if any are defined. If this class does not have any
1540: * defined traits, this will return an empty array.
1541: *
1542: * @return list<ReflectionClass>
1543: */
1544: public function getTraits(): array
1545: {
1546: if ($this->cachedTraits !== null) {
1547: return $this->cachedTraits;
1548: }
1549:
1550: if ($this->isTrait && $this->isOnTraitCycle()) {
1551: return $this->cachedTraits = [];
1552: }
1553:
1554: $traits = [];
1555: foreach ($this->traitClassNames as $traitClassName) {
1556: try {
1557: $traits[] = $this->reflector->reflectClass($traitClassName);
1558: } catch (IdentifierNotFound $exception) {
1559: // pass
1560: }
1561: }
1562:
1563: return $this->cachedTraits = $traits;
1564: }
1565:
1566: /**
1567: * @param list<class-string> $interfaceClassNames
1568: *
1569: * @return list<class-string>
1570: */
1571: private function addStringableInterfaceClassName(array $interfaceClassNames): array
1572: {
1573: if (BetterReflection::$phpVersion < 80000) {
1574: return $interfaceClassNames;
1575: }
1576:
1577: /** @psalm-var class-string $stringableClassName */
1578: $stringableClassName = Stringable::class;
1579:
1580: if ($this->isInterface && $this->getName() === $stringableClassName) {
1581: return $interfaceClassNames;
1582: }
1583:
1584: if (in_array($stringableClassName, $interfaceClassNames, true)) {
1585: return $interfaceClassNames;
1586: }
1587:
1588: $methods = $this->immediateMethods;
1589: foreach ($this->getTraits() as $trait) {
1590: $methods += $trait->immediateMethods;
1591: }
1592:
1593: foreach (array_keys($methods) as $immediateMethodName) {
1594: if (strtolower($immediateMethodName) === '__tostring') {
1595: try {
1596: $interfaceClassNames[] = $stringableClassName;
1597: } catch (IdentifierNotFound $exception) {
1598: // Stringable interface does not exist on target PHP version
1599: }
1600:
1601: // @infection-ignore-all Break_: There's no difference between break and continue - break is just optimization
1602: break;
1603: }
1604: }
1605:
1606: return $interfaceClassNames;
1607: }
1608:
1609: /**
1610: * @param list<class-string> $interfaceClassNames
1611: *
1612: * @return list<class-string>
1613: */
1614: private function addEnumInterfaceClassNames(array $interfaceClassNames): array
1615: {
1616: assert($this->isEnum === true);
1617:
1618: $interfaceClassNames[] = UnitEnum::class;
1619:
1620: if ($this->isBackedEnum) {
1621: $interfaceClassNames[] = BackedEnum::class;
1622: }
1623:
1624: return $interfaceClassNames;
1625: }
1626:
1627: /** @return list<trait-string> */
1628: public function getTraitClassNames(): array
1629: {
1630: return $this->traitClassNames;
1631: }
1632:
1633: /**
1634: * Get the names of the traits used as an array of strings, if any are
1635: * defined. If this class does not have any defined traits, this will
1636: * return an empty array.
1637: *
1638: * @return list<trait-string>
1639: */
1640: public function getTraitNames(): array
1641: {
1642: return array_map(
1643: static function (ReflectionClass $trait): string {
1644: /** @psalm-var trait-string $traitName */
1645: $traitName = $trait->getName();
1646:
1647: return $traitName;
1648: },
1649: $this->getTraits(),
1650: );
1651: }
1652:
1653: /**
1654: * Return a list of the aliases used when importing traits for this class.
1655: * The returned array is in key/value pair in this format:.
1656: *
1657: * 'aliasedMethodName' => 'ActualClass::actualMethod'
1658: *
1659: * @return array<non-empty-string, non-empty-string>
1660: *
1661: * @example
1662: * // When reflecting a class such as:
1663: * class Foo
1664: * {
1665: * use MyTrait {
1666: * myTraitMethod as myAliasedMethod;
1667: * }
1668: * }
1669: * // This method would return
1670: * // ['myAliasedMethod' => 'MyTrait::myTraitMethod']
1671: */
1672: public function getTraitAliases(): array
1673: {
1674: if ($this->traitsData['aliases'] === []) {
1675: return [];
1676: }
1677:
1678: $traits = [];
1679: foreach ($this->getTraits() as $trait) {
1680: $traits[$trait->getName()] = $trait;
1681: }
1682:
1683: $traitAliases = [];
1684:
1685: foreach ($this->traitsData['aliases'] as $traitClassName => $traitAliasDefinitions) {
1686: foreach ($traitAliasDefinitions as $traitAliasDefinition) {
1687: if (! array_key_exists($traitClassName, $traits)) {
1688: continue;
1689: }
1690:
1691: if (! $traits[$traitClassName]->hasMethod($traitAliasDefinition['method'])) {
1692: continue;
1693: }
1694:
1695: $traitAliases[$traitAliasDefinition['alias']] = $this->traitsData['hashes'][$traitAliasDefinition['hash']];
1696: }
1697: }
1698:
1699: return $traitAliases;
1700: }
1701:
1702: /**
1703: * Returns data when importing traits for this class:
1704: *
1705: * 'aliases': List of the aliases used when importing traits. In format:
1706: *
1707: * 'traitClassName' => ['alias' => 'aliasedMethodName', 'method' => 'actualMethodName', 'hash' => 'traitClassName::actualMethodName'],
1708: *
1709: * Example:
1710: * // When reflecting a code such as:
1711: *
1712: * use MyTrait {
1713: * myTraitMethod as myAliasedMethod;
1714: * }
1715: *
1716: * // This method would return
1717: * // ['MyTrait' => ['alias' => 'myAliasedMethod', 'method' => 'myTraitMethod', 'hash' => 'mytrait::mytraitmethod']]
1718: *
1719: * 'modifiers': Used modifiers when importing traits. In format:
1720: *
1721: * 'methodName' => 'modifier'
1722: *
1723: * Example:
1724: * // When reflecting a code such as:
1725: *
1726: * use MyTrait {
1727: * myTraitMethod as public;
1728: * }
1729: *
1730: * // This method would return
1731: * // ['myTraitMethod' => 1]
1732: *
1733: * 'precedences': Precedences used when importing traits. In format:
1734: *
1735: * 'Class::method' => 'Class::method'
1736: *
1737: * Example:
1738: * // When reflecting a code such as:
1739: *
1740: * use MyTrait, MyTrait2 {
1741: * MyTrait2::foo insteadof MyTrait1;
1742: * }
1743: *
1744: * // This method would return
1745: * // ['MyTrait1::foo' => 'MyTrait2::foo']
1746: *
1747: * @return array{
1748: * aliases: array<trait-string, list<array{alias: non-empty-string, method: non-empty-string, hash: non-empty-string}>>,
1749: * modifiers: array<non-empty-string, int-mask-of<ReflectionMethodAdapter::IS_*>>,
1750: * precedences: array<non-empty-string, non-empty-string>,
1751: * hashes: array<non-empty-string, non-empty-string>,
1752: * }
1753: * @param ClassNode|InterfaceNode|TraitNode|EnumNode $node
1754: */
1755: private function computeTraitsData($node): array
1756: {
1757: $traitsData = [
1758: 'aliases' => [],
1759: 'modifiers' => [],
1760: 'precedences' => [],
1761: 'hashes' => [],
1762: ];
1763:
1764: foreach ($node->getTraitUses() as $traitUsage) {
1765: foreach ($traitUsage->adaptations as $adaptation) {
1766: $usedTraits = $adaptation->trait !== null ? [$adaptation->trait] : $traitUsage->traits;
1767: $traitsData = $this->processTraitAdaptation($adaptation, $usedTraits, $traitsData);
1768: }
1769: }
1770:
1771: return $traitsData;
1772: }
1773:
1774: /**
1775: * @phpcs:disable Squiz.Commenting.FunctionComment.MissingParamName
1776: *
1777: * @param array<array-key, Node\Name> $usedTraits
1778: * @param array{
1779: * aliases: array<trait-string, list<array{alias: non-empty-string, method: non-empty-string, hash: non-empty-string}>>,
1780: * modifiers: array<non-empty-string, int-mask-of<ReflectionMethodAdapter::IS_*>>,
1781: * precedences: array<non-empty-string, non-empty-string>,
1782: * hashes: array<non-empty-string, non-empty-string>,
1783: * } $traitsData
1784: *
1785: * @return array{
1786: * aliases: array<trait-string, list<array{alias: non-empty-string, method: non-empty-string, hash: non-empty-string}>>,
1787: * modifiers: array<non-empty-string, int-mask-of<ReflectionMethodAdapter::IS_*>>,
1788: * precedences: array<non-empty-string, non-empty-string>,
1789: * hashes: array<non-empty-string, non-empty-string>,
1790: * }
1791: */
1792: private function processTraitAdaptation(Node\Stmt\TraitUseAdaptation $adaptation, array $usedTraits, array $traitsData): array
1793: {
1794: foreach ($usedTraits as $usedTrait) {
1795: $methodHash = $this->methodHash($usedTrait->toString(), $adaptation->method->toString());
1796: $lowerCasedMethodHash = $this->lowerCasedMethodHash($usedTrait->toString(), $adaptation->method->toString());
1797:
1798: $traitsData['hashes'][$lowerCasedMethodHash] = $methodHash;
1799:
1800: if ($adaptation instanceof Node\Stmt\TraitUseAdaptation\Alias) {
1801: if ($adaptation->newModifier !== null) {
1802: /** @var int-mask-of<ReflectionMethodAdapter::IS_*> $modifier */
1803: $modifier = $adaptation->newModifier;
1804: $traitsData['modifiers'][$lowerCasedMethodHash] = $modifier;
1805: }
1806:
1807: if ($adaptation->newName !== null) {
1808: // We need to save all possible combinations of trait and method names
1809: // The real aliases will be filtered in getters
1810: /** @var trait-string $usedTraitClassName */
1811: $usedTraitClassName = $usedTrait->toString();
1812: $traitsData['aliases'][$usedTraitClassName][] = [
1813: 'alias' => $adaptation->newName->name,
1814: 'method' => $adaptation->method->toString(),
1815: 'hash' => $lowerCasedMethodHash,
1816: ];
1817: }
1818: } elseif ($adaptation instanceof Node\Stmt\TraitUseAdaptation\Precedence) {
1819: foreach ($adaptation->insteadof as $insteadof) {
1820: $adaptationNameHash = $this->lowerCasedMethodHash($insteadof->toString(), $adaptation->method->toString());
1821:
1822: $traitsData['precedences'][$adaptationNameHash] = $lowerCasedMethodHash;
1823: }
1824: }
1825: }
1826:
1827: return $traitsData;
1828: }
1829:
1830: /**
1831: * @return non-empty-string
1832: *
1833: * @psalm-pure
1834: */
1835: private function methodHash(string $className, string $methodName): string
1836: {
1837: return sprintf(
1838: '%s::%s',
1839: $className,
1840: $methodName,
1841: );
1842: }
1843:
1844: /** @return non-empty-string */
1845: private function lowerCasedMethodHash(string $className, string $methodName): string
1846: {
1847: return strtolower($this->methodHash($className, $methodName));
1848: }
1849:
1850: /** @return list<class-string> */
1851: public function getInterfaceClassNames(): array
1852: {
1853: $implementsClassNames = $this->implementsClassNames;
1854:
1855: if ($this->isEnum) {
1856: $implementsClassNames = $this->addEnumInterfaceClassNames($implementsClassNames);
1857: }
1858:
1859: return $this->addStringableInterfaceClassName($implementsClassNames);
1860: }
1861:
1862: /**
1863: * Gets the interfaces.
1864: *
1865: * @link https://php.net/manual/en/reflectionclass.getinterfaces.php
1866: *
1867: * @return array<class-string, self> An associative array of interfaces, with keys as interface names and the array
1868: * values as {@see ReflectionClass} objects.
1869: */
1870: public function getInterfaces(): array
1871: {
1872: if ($this->cachedInterfaces !== null) {
1873: return $this->cachedInterfaces;
1874: }
1875:
1876: $interfaces = array_merge(
1877: [$this->getCurrentClassImplementedInterfacesIndexedByName()],
1878: array_map(
1879: static fn (self $parentClass): array => $parentClass->getCurrentClassImplementedInterfacesIndexedByName(),
1880: $this->getParentClasses(),
1881: ),
1882: );
1883:
1884: return $this->cachedInterfaces = array_merge(...array_reverse($interfaces));
1885: }
1886:
1887: /**
1888: * Get only the interfaces that this class implements (i.e. do not search
1889: * up parent classes etc.)
1890: *
1891: * @return array<class-string, self>
1892: */
1893: public function getImmediateInterfaces(): array
1894: {
1895: if ($this->isTrait) {
1896: return [];
1897: }
1898:
1899: if ($this->isInterface && $this->isOnInterfaceCycle()) {
1900: return [];
1901: }
1902:
1903: $interfaces = [];
1904: foreach ($this->getInterfaceClassNames() as $interfaceClassName) {
1905: try {
1906: $interfaces[$interfaceClassName] = $this->reflector->reflectClass($interfaceClassName);
1907: } catch (IdentifierNotFound $exception) {
1908: continue;
1909: }
1910: }
1911:
1912: return $interfaces;
1913: }
1914:
1915: /**
1916: * Gets the interface names.
1917: *
1918: * @link https://php.net/manual/en/reflectionclass.getinterfacenames.php
1919: *
1920: * @return list<class-string> A numerical array with interface names as the values.
1921: */
1922: public function getInterfaceNames(): array
1923: {
1924: if ($this->cachedInterfaceNames !== null) {
1925: return $this->cachedInterfaceNames;
1926: }
1927:
1928: return $this->cachedInterfaceNames = array_values(array_map(
1929: static fn (self $interface): string => $interface->getName(),
1930: $this->getInterfaces(),
1931: ));
1932: }
1933:
1934: /**
1935: * Checks whether the given object is an instance.
1936: *
1937: * @link https://php.net/manual/en/reflectionclass.isinstance.php
1938: */
1939: public function isInstance(object $object): bool
1940: {
1941: $className = $this->getName();
1942:
1943: // note: since $object was loaded, we can safely assume that $className is available in the current
1944: // php script execution context
1945: return $object instanceof $className;
1946: }
1947:
1948: /**
1949: * Checks whether the given class string is a subclass of this class.
1950: *
1951: * @link https://php.net/manual/en/reflectionclass.isinstance.php
1952: */
1953: public function isSubclassOf(string $className): bool
1954: {
1955: return in_array(
1956: ltrim($className, '\\'),
1957: $this->getParentClassNames(),
1958: true,
1959: );
1960: }
1961:
1962: /**
1963: * Checks whether this class implements the given interface.
1964: *
1965: * @link https://php.net/manual/en/reflectionclass.implementsinterface.php
1966: */
1967: public function implementsInterface(string $interfaceName): bool
1968: {
1969: return in_array(ltrim($interfaceName, '\\'), $this->getInterfaceNames(), true);
1970: }
1971:
1972: /**
1973: * Checks whether this reflection is an instantiable class
1974: *
1975: * @link https://php.net/manual/en/reflectionclass.isinstantiable.php
1976: */
1977: public function isInstantiable(): bool
1978: {
1979: // @TODO doesn't consider internal non-instantiable classes yet.
1980:
1981: if ($this->isAbstract()) {
1982: return false;
1983: }
1984:
1985: if ($this->isInterface()) {
1986: return false;
1987: }
1988:
1989: if ($this->isTrait()) {
1990: return false;
1991: }
1992:
1993: $constructor = $this->getConstructor();
1994:
1995: if ($constructor === null) {
1996: return true;
1997: }
1998:
1999: return $constructor->isPublic();
2000: }
2001:
2002: /**
2003: * Checks whether this is a reflection of a class that supports the clone operator
2004: *
2005: * @link https://php.net/manual/en/reflectionclass.iscloneable.php
2006: */
2007: public function isCloneable(): bool
2008: {
2009: if (! $this->isInstantiable()) {
2010: return false;
2011: }
2012:
2013: $cloneMethod = $this->getMethod('__clone');
2014:
2015: if ($cloneMethod === null) {
2016: return true;
2017: }
2018:
2019: return $cloneMethod->isPublic();
2020: }
2021:
2022: /**
2023: * Checks if iterateable
2024: *
2025: * @link https://php.net/manual/en/reflectionclass.isiterateable.php
2026: */
2027: public function isIterateable(): bool
2028: {
2029: return $this->isInstantiable() && $this->implementsInterface(Traversable::class);
2030: }
2031:
2032: public function isEnum(): bool
2033: {
2034: return $this->isEnum;
2035: }
2036:
2037: /** @return array<class-string, ReflectionClass> */
2038: private function getCurrentClassImplementedInterfacesIndexedByName(): array
2039: {
2040: if ($this->isTrait) {
2041: return [];
2042: }
2043:
2044: if ($this->isInterface) {
2045: // assumption: first key is the current interface
2046: return array_slice($this->getInterfacesHierarchy(AlreadyVisitedClasses::createEmpty()), 1);
2047: }
2048:
2049: $interfaces = [];
2050: foreach ($this->getInterfaceClassNames() as $name) {
2051: try {
2052: $interface = $this->reflector->reflectClass($name);
2053: foreach ($interface->getInterfacesHierarchy(AlreadyVisitedClasses::createEmpty()) as $n => $i) {
2054: $interfaces[$n] = $i;
2055: }
2056: } catch (IdentifierNotFound $exception) {
2057: continue;
2058: }
2059: }
2060:
2061: return $interfaces;
2062: }
2063:
2064: /**
2065: * This method allows us to retrieve all interfaces parent of this interface. Do not use on class nodes!
2066: *
2067: * @return array<class-string, ReflectionClass> parent interfaces of this interface
2068: */
2069: private function getInterfacesHierarchy(AlreadyVisitedClasses $alreadyVisitedClasses): array
2070: {
2071: if (! $this->isInterface) {
2072: return [];
2073: }
2074:
2075: $interfaceClassName = $this->getName();
2076: $alreadyVisitedClasses->push($interfaceClassName);
2077:
2078: /** @var array<class-string, self> $interfaces */
2079: $interfaces = [$interfaceClassName => $this];
2080: foreach ($this->getImmediateInterfaces() as $interface) {
2081: $alreadyVisitedClassesCopyForInterface = clone $alreadyVisitedClasses;
2082: foreach ($interface->getInterfacesHierarchy($alreadyVisitedClassesCopyForInterface) as $extendedInterfaceName => $extendedInterface) {
2083: $interfaces[$extendedInterfaceName] = $extendedInterface;
2084: }
2085: }
2086:
2087: return $interfaces;
2088: }
2089:
2090: /**
2091: * Get the value of a static property, if it exists. Throws a
2092: * PropertyDoesNotExist exception if it does not exist or is not static.
2093: * (note, differs very slightly from internal reflection behaviour)
2094: *
2095: * @param non-empty-string $propertyName
2096: *
2097: * @throws ClassDoesNotExist
2098: * @throws NoObjectProvided
2099: * @throws NotAnObject
2100: * @throws ObjectNotInstanceOfClass
2101: * @return mixed
2102: */
2103: public function getStaticPropertyValue(string $propertyName)
2104: {
2105: $property = $this->getProperty($propertyName);
2106:
2107: if (! $property || ! $property->isStatic()) {
2108: throw PropertyDoesNotExist::fromName($propertyName);
2109: }
2110:
2111: return $property->getValue();
2112: }
2113:
2114: /**
2115: * Set the value of a static property
2116: *
2117: * @param non-empty-string $propertyName
2118: *
2119: * @throws ClassDoesNotExist
2120: * @throws NoObjectProvided
2121: * @throws NotAnObject
2122: * @throws ObjectNotInstanceOfClass
2123: * @param mixed $value
2124: */
2125: public function setStaticPropertyValue(string $propertyName, $value): void
2126: {
2127: $property = $this->getProperty($propertyName);
2128:
2129: if (! $property || ! $property->isStatic()) {
2130: throw PropertyDoesNotExist::fromName($propertyName);
2131: }
2132:
2133: $property->setValue($value);
2134: }
2135:
2136: /** @return array<non-empty-string, mixed> */
2137: public function getStaticProperties(): array
2138: {
2139: $staticProperties = [];
2140:
2141: foreach ($this->getProperties() as $property) {
2142: if (! $property->isStatic()) {
2143: continue;
2144: }
2145:
2146: /** @psalm-suppress MixedAssignment */
2147: $staticProperties[$property->getName()] = $property->getValue();
2148: }
2149:
2150: return $staticProperties;
2151: }
2152:
2153: /** @return list<ReflectionAttribute> */
2154: public function getAttributes(): array
2155: {
2156: return $this->attributes;
2157: }
2158:
2159: /** @return list<ReflectionAttribute> */
2160: public function getAttributesByName(string $name): array
2161: {
2162: $attributes = $this->getAttributes();
2163:
2164: if ($attributes === []) {
2165: return [];
2166: }
2167:
2168: return ReflectionAttributeHelper::filterAttributesByName($attributes, $name);
2169: }
2170:
2171: /**
2172: * @param class-string $className
2173: *
2174: * @return list<ReflectionAttribute>
2175: */
2176: public function getAttributesByInstance(string $className): array
2177: {
2178: return ReflectionAttributeHelper::filterAttributesByInstance($this->getAttributes(), $className);
2179: }
2180: }
2181: