1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type;
4:
5: use PhpParser\Node\Identifier;
6: use PHPStan\Analyser\OutOfClassScope;
7: use PHPStan\Php\PhpVersion;
8: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode;
9: use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode;
10: use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
11: use PHPStan\PhpDocParser\Ast\Type\ObjectShapeItemNode;
12: use PHPStan\PhpDocParser\Ast\Type\ObjectShapeNode;
13: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
14: use PHPStan\Reflection\ClassMemberAccessAnswerer;
15: use PHPStan\Reflection\ExtendedPropertyReflection;
16: use PHPStan\Reflection\MissingPropertyFromReflectionException;
17: use PHPStan\Reflection\Php\UniversalObjectCratesClassReflectionExtension;
18: use PHPStan\Reflection\ReflectionProviderStaticAccessor;
19: use PHPStan\Reflection\Type\CallbackUnresolvedPropertyPrototypeReflection;
20: use PHPStan\Reflection\Type\UnresolvedPropertyPrototypeReflection;
21: use PHPStan\ShouldNotHappenException;
22: use PHPStan\TrinaryLogic;
23: use PHPStan\Turbo\ShadowedByTurboExtension;
24: use PHPStan\Type\Accessory\HasPropertyType;
25: use PHPStan\Type\Constant\ConstantArrayType;
26: use PHPStan\Type\Constant\ConstantStringType;
27: use PHPStan\Type\Enum\EnumCaseObjectType;
28: use PHPStan\Type\Generic\GenericClassStringType;
29: use PHPStan\Type\Generic\TemplateTypeMap;
30: use PHPStan\Type\Generic\TemplateTypeVariance;
31: use PHPStan\Type\Traits\NonGeneralizableTypeTrait;
32: use PHPStan\Type\Traits\ObjectTypeTrait;
33: use PHPStan\Type\Traits\OperatorTypeTrait;
34: use PHPStan\Type\Traits\UndecidedComparisonTypeTrait;
35: use function array_filter;
36: use function array_key_exists;
37: use function array_values;
38: use function count;
39: use function implode;
40: use function in_array;
41: use function sprintf;
42:
43: /** @api */
44: #[InstanceofDeprecated(insteadUse: 'Type::isObject() and Type::hasProperty()')]
45: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../turbo-ext/src/ObjectShapeType.cpp')]
46: class ObjectShapeType implements Type
47: {
48:
49: use ObjectTypeTrait;
50: use UndecidedComparisonTypeTrait;
51: use NonGeneralizableTypeTrait;
52: use OperatorTypeTrait;
53:
54: /**
55: * @api
56: * @param array<int|string, Type> $properties
57: * @param list<int|string> $optionalProperties
58: */
59: public function __construct(private array $properties, private array $optionalProperties)
60: {
61: }
62:
63: /**
64: * @return array<int|string, Type>
65: */
66: public function getProperties(): array
67: {
68: return $this->properties;
69: }
70:
71: /**
72: * @return list<int|string>
73: */
74: public function getOptionalProperties(): array
75: {
76: return $this->optionalProperties;
77: }
78:
79: public function getReferencedClasses(): array
80: {
81: $classes = [];
82: foreach ($this->properties as $propertyType) {
83: foreach ($propertyType->getReferencedClasses() as $referencedClass) {
84: $classes[] = $referencedClass;
85: }
86: }
87:
88: return $classes;
89: }
90:
91: public function getObjectClassNames(): array
92: {
93: return [];
94: }
95:
96: public function getObjectClassReflections(): array
97: {
98: return [];
99: }
100:
101: public function getClassStringType(): Type
102: {
103: return new GenericClassStringType($this);
104: }
105:
106: public function hasProperty(string $propertyName): TrinaryLogic
107: {
108: return $this->hasInstanceProperty($propertyName);
109: }
110:
111: public function getProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
112: {
113: return $this->getInstanceProperty($propertyName, $scope);
114: }
115:
116: public function getUnresolvedPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
117: {
118: return $this->getUnresolvedInstancePropertyPrototype($propertyName, $scope);
119: }
120:
121: public function hasInstanceProperty(string $propertyName): TrinaryLogic
122: {
123: if (!array_key_exists($propertyName, $this->properties)) {
124: return TrinaryLogic::createNo();
125: }
126:
127: if (in_array($propertyName, $this->optionalProperties, true)) {
128: return TrinaryLogic::createMaybe();
129: }
130:
131: return TrinaryLogic::createYes();
132: }
133:
134: public function getInstanceProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
135: {
136: return $this->getUnresolvedInstancePropertyPrototype($propertyName, $scope)->getTransformedProperty();
137: }
138:
139: public function getUnresolvedInstancePropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
140: {
141: if (!array_key_exists($propertyName, $this->properties)) {
142: throw new ShouldNotHappenException();
143: }
144:
145: $property = new ObjectShapePropertyReflection($propertyName, $this->properties[$propertyName]);
146: return new CallbackUnresolvedPropertyPrototypeReflection(
147: $property,
148: $property->getDeclaringClass(),
149: false,
150: static fn (Type $type): Type => $type,
151: );
152: }
153:
154: public function hasStaticProperty(string $propertyName): TrinaryLogic
155: {
156: return TrinaryLogic::createNo();
157: }
158:
159: public function getStaticProperty(string $propertyName, ClassMemberAccessAnswerer $scope): ExtendedPropertyReflection
160: {
161: throw new ShouldNotHappenException();
162: }
163:
164: public function getUnresolvedStaticPropertyPrototype(string $propertyName, ClassMemberAccessAnswerer $scope): UnresolvedPropertyPrototypeReflection
165: {
166: throw new ShouldNotHappenException();
167: }
168:
169: public function accepts(Type $type, bool $strictTypes): AcceptsResult
170: {
171: if ($type instanceof CompoundType) {
172: return $type->isAcceptedBy($this, $strictTypes);
173: }
174:
175: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
176: foreach ($type->getObjectClassReflections() as $classReflection) {
177: if (!UniversalObjectCratesClassReflectionExtension::isUniversalObjectCrate(
178: $reflectionProvider,
179: $classReflection,
180: )) {
181: continue;
182: }
183:
184: return AcceptsResult::createMaybe();
185: }
186:
187: $result = AcceptsResult::createYes();
188: $scope = new OutOfClassScope();
189: foreach ($this->properties as $propertyName => $propertyType) {
190: $typeHasProperty = $type->hasInstanceProperty((string) $propertyName);
191: $hasProperty = new AcceptsResult(
192: $typeHasProperty,
193: $typeHasProperty->yes() ? [] : [
194: sprintf(
195: '%s %s have property $%s.',
196: $type->describe(VerbosityLevel::typeOnly()),
197: $typeHasProperty->no() ? 'does not' : 'might not',
198: $propertyName,
199: ),
200: ],
201: );
202: if (!$hasProperty->yes() && $type->hasStaticProperty((string) $propertyName)->yes()) {
203: $result = $result->and(new AcceptsResult(TrinaryLogic::createNo(), [
204: sprintf('Property %s::$%s is static.', $type->getStaticProperty((string) $propertyName, $scope)->getDeclaringClass()->getDisplayName(), $propertyName),
205: ]));
206: continue;
207: }
208: if ($hasProperty->no()) {
209: if (in_array($propertyName, $this->optionalProperties, true)) {
210: continue;
211: }
212: $result = $result->and($hasProperty);
213: continue;
214: }
215: if ($hasProperty->maybe()) {
216: if (!in_array($propertyName, $this->optionalProperties, true)) {
217: $result = $result->and($hasProperty);
218: continue;
219:
220: }
221:
222: $hasProperty = AcceptsResult::createYes();
223: }
224:
225: $result = $result->and($hasProperty);
226: try {
227: $otherProperty = $type->getInstanceProperty((string) $propertyName, $scope);
228: } catch (MissingPropertyFromReflectionException) {
229: continue;
230: }
231:
232: if (!$otherProperty->isPublic()) {
233: return new AcceptsResult(TrinaryLogic::createNo(), [
234: sprintf('Property %s::$%s is not public.', $otherProperty->getDeclaringClass()->getDisplayName(), $propertyName),
235: ]);
236: }
237:
238: if ($otherProperty->isStatic()) {
239: return new AcceptsResult(TrinaryLogic::createNo(), [
240: sprintf('Property %s::$%s is static.', $otherProperty->getDeclaringClass()->getDisplayName(), $propertyName),
241: ]);
242: }
243:
244: if (!$otherProperty->isReadable()) {
245: return new AcceptsResult(TrinaryLogic::createNo(), [
246: sprintf('Property %s::$%s is not readable.', $otherProperty->getDeclaringClass()->getDisplayName(), $propertyName),
247: ]);
248: }
249:
250: $otherPropertyType = $otherProperty->getReadableType();
251: $verbosity = VerbosityLevel::getRecommendedLevelByType($propertyType, $otherPropertyType);
252: $acceptsValue = $propertyType->accepts($otherPropertyType, $strictTypes)->decorateReasons(
253: static fn (string $reason) => sprintf(
254: 'Property ($%s) type %s does not accept type %s: %s',
255: $propertyName,
256: $propertyType->describe($verbosity),
257: $otherPropertyType->describe($verbosity),
258: $reason,
259: ),
260: );
261: if (!$acceptsValue->yes() && count($acceptsValue->reasons) === 0) {
262: $acceptsValue = new AcceptsResult($acceptsValue->result, [
263: sprintf(
264: 'Property ($%s) type %s does not accept type %s.',
265: $propertyName,
266: $propertyType->describe($verbosity),
267: $otherPropertyType->describe($verbosity),
268: ),
269: ]);
270: }
271: if ($acceptsValue->no()) {
272: return $acceptsValue;
273: }
274: $result = $result->and($acceptsValue);
275: }
276:
277: return $result->and(new AcceptsResult($type->isObject(), []));
278: }
279:
280: public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
281: {
282: if ($type instanceof CompoundType) {
283: return $type->isSubTypeOf($this);
284: }
285:
286: if ($type instanceof ObjectWithoutClassType) {
287: return IsSuperTypeOfResult::createMaybe();
288: }
289:
290: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
291: foreach ($type->getObjectClassReflections() as $classReflection) {
292: if (!UniversalObjectCratesClassReflectionExtension::isUniversalObjectCrate(
293: $reflectionProvider,
294: $classReflection,
295: )) {
296: continue;
297: }
298:
299: return IsSuperTypeOfResult::createMaybe();
300: }
301:
302: $result = IsSuperTypeOfResult::createYes();
303: $scope = new OutOfClassScope();
304: foreach ($this->properties as $propertyName => $propertyType) {
305: $typeHasProperty = $type->hasInstanceProperty((string) $propertyName);
306: $hasProperty = new IsSuperTypeOfResult(
307: $typeHasProperty,
308: $typeHasProperty->yes() ? [] : [
309: sprintf(
310: '%s %s have property $%s.',
311: $type->describe(VerbosityLevel::typeOnly()),
312: $typeHasProperty->no() ? 'does not' : 'might not',
313: $propertyName,
314: ),
315: ],
316: );
317: if ($hasProperty->no()) {
318: if (in_array($propertyName, $this->optionalProperties, true)) {
319: continue;
320: }
321: $result = $result->and($hasProperty);
322: continue;
323: }
324: if ($hasProperty->maybe()) {
325: if (!in_array($propertyName, $this->optionalProperties, true)) {
326: $result = $result->and($hasProperty);
327: continue;
328: }
329:
330: $hasProperty = IsSuperTypeOfResult::createYes();
331: }
332:
333: $result = $result->and($hasProperty);
334: try {
335: $otherProperty = $type->getInstanceProperty((string) $propertyName, $scope);
336: } catch (MissingPropertyFromReflectionException) {
337: continue;
338: }
339:
340: if (!$otherProperty->isPublic()) {
341: return IsSuperTypeOfResult::createNo([
342: sprintf('Property %s::$%s is not public.', $otherProperty->getDeclaringClass()->getDisplayName(), $propertyName),
343: ]);
344: }
345:
346: if ($otherProperty->isStatic()) {
347: return IsSuperTypeOfResult::createNo([
348: sprintf('Property %s::$%s is static.', $otherProperty->getDeclaringClass()->getDisplayName(), $propertyName),
349: ]);
350: }
351:
352: if (!$otherProperty->isReadable()) {
353: return IsSuperTypeOfResult::createNo([
354: sprintf('Property %s::$%s is not readable.', $otherProperty->getDeclaringClass()->getDisplayName(), $propertyName),
355: ]);
356: }
357:
358: $otherPropertyType = $otherProperty->getReadableType();
359: $isSuperType = $propertyType->isSuperTypeOf($otherPropertyType);
360: if ($isSuperType->no()) {
361: return $isSuperType;
362: }
363: $result = $result->and($isSuperType);
364: }
365:
366: return $result->and(IsSuperTypeOfResult::createFromTrinaryLogic($type->isObject()));
367: }
368:
369: public function equals(Type $type): bool
370: {
371: if (!$type instanceof self) {
372: return false;
373: }
374:
375: if (count($this->properties) !== count($type->properties)) {
376: return false;
377: }
378:
379: foreach ($this->properties as $name => $propertyType) {
380: if (!array_key_exists($name, $type->properties)) {
381: return false;
382: }
383:
384: if (!$propertyType->equals($type->properties[$name])) {
385: return false;
386: }
387: }
388:
389: if (count($this->optionalProperties) !== count($type->optionalProperties)) {
390: return false;
391: }
392:
393: foreach ($this->optionalProperties as $name) {
394: if (in_array($name, $type->optionalProperties, true)) {
395: continue;
396: }
397:
398: return false;
399: }
400:
401: return true;
402: }
403:
404: public function tryRemove(Type $typeToRemove): ?Type
405: {
406: if ($typeToRemove instanceof HasPropertyType) {
407: $properties = $this->properties;
408: unset($properties[$typeToRemove->getPropertyName()]);
409: $optionalProperties = array_values(array_filter($this->optionalProperties, static fn (int|string $propertyName) => $propertyName !== $typeToRemove->getPropertyName()));
410:
411: return new self($properties, $optionalProperties);
412: }
413:
414: return null;
415: }
416:
417: public function makePropertyRequired(string $propertyName): self
418: {
419: if (array_key_exists($propertyName, $this->properties)) {
420: $optionalProperties = array_values(array_filter($this->optionalProperties, static fn (int|string $currentPropertyName) => $currentPropertyName !== $propertyName));
421:
422: return new self($this->properties, $optionalProperties);
423: }
424:
425: return $this;
426: }
427:
428: public function inferTemplateTypes(Type $receivedType): TemplateTypeMap
429: {
430: if ($receivedType instanceof UnionType || $receivedType instanceof IntersectionType) {
431: return $receivedType->inferTemplateTypesOn($this);
432: }
433:
434: if ($receivedType instanceof self) {
435: $typeMap = TemplateTypeMap::createEmpty();
436: $scope = new OutOfClassScope();
437: foreach ($this->properties as $name => $propertyType) {
438: if ($receivedType->hasInstanceProperty((string) $name)->no()) {
439: continue;
440: }
441:
442: try {
443: $receivedProperty = $receivedType->getInstanceProperty((string) $name, $scope);
444: } catch (MissingPropertyFromReflectionException) {
445: continue;
446: }
447: if (!$receivedProperty->isPublic()) {
448: continue;
449: }
450: if ($receivedProperty->isStatic()) {
451: continue;
452: }
453: $receivedPropertyType = $receivedProperty->getReadableType();
454: $typeMap = $typeMap->union($propertyType->inferTemplateTypes($receivedPropertyType));
455: }
456:
457: return $typeMap;
458: }
459:
460: return TemplateTypeMap::createEmpty();
461: }
462:
463: public function getReferencedTemplateTypes(TemplateTypeVariance $positionVariance): array
464: {
465: $variance = $positionVariance->compose(TemplateTypeVariance::createCovariant());
466: $references = [];
467: foreach ($this->properties as $propertyType) {
468: foreach ($propertyType->getReferencedTemplateTypes($variance) as $reference) {
469: $references[] = $reference;
470: }
471: }
472:
473: return $references;
474: }
475:
476: public function describe(VerbosityLevel $level): string
477: {
478: $callback = function () use ($level): string {
479: $items = [];
480: foreach ($this->properties as $name => $propertyType) {
481: $optional = in_array($name, $this->optionalProperties, true);
482: $items[] = sprintf('%s%s: %s', $name, $optional ? '?' : '', $propertyType->describe($level));
483: }
484: return sprintf('object{%s}', implode(', ', $items));
485: };
486: return $level->handle(
487: $callback,
488: $callback,
489: );
490: }
491:
492: public function getEnumCases(): array
493: {
494: return [];
495: }
496:
497: public function getEnumCaseObject(): ?EnumCaseObjectType
498: {
499: return null;
500: }
501:
502: public function traverse(callable $cb): Type
503: {
504: $properties = [];
505: $stillOriginal = true;
506:
507: foreach ($this->properties as $name => $propertyType) {
508: $transformed = $cb($propertyType);
509: if ($transformed !== $propertyType) {
510: $stillOriginal = false;
511: }
512:
513: $properties[$name] = $transformed;
514: }
515:
516: if ($stillOriginal) {
517: return $this;
518: }
519:
520: return new self($properties, $this->optionalProperties);
521: }
522:
523: public function traverseSimultaneously(Type $right, callable $cb): Type
524: {
525: if (!$right->isObject()->yes()) {
526: return $this;
527: }
528:
529: $properties = [];
530: $stillOriginal = true;
531:
532: $scope = new OutOfClassScope();
533: foreach ($this->properties as $name => $propertyType) {
534: if (!$right->hasInstanceProperty((string) $name)->yes()) {
535: return $this;
536: }
537: $transformed = $cb($propertyType, $right->getInstanceProperty((string) $name, $scope)->getReadableType());
538: if ($transformed !== $propertyType) {
539: $stillOriginal = false;
540: }
541:
542: $properties[$name] = $transformed;
543: }
544:
545: if ($stillOriginal) {
546: return $this;
547: }
548:
549: return new self($properties, $this->optionalProperties);
550: }
551:
552: public function arithmeticPower(Type $exponent, PhpVersion $phpVersion): Type
553: {
554: if (!$exponent instanceof NeverType && !$this->isSuperTypeOf($exponent)->no()) {
555: return TypeCombinator::union($this, $exponent);
556: }
557:
558: return new BenevolentUnionType([
559: new FloatType(),
560: new IntegerType(),
561: ]);
562: }
563:
564: public function getFiniteTypes(): array
565: {
566: return [];
567: }
568:
569: public function toPhpDocNode(): TypeNode
570: {
571: $items = [];
572: foreach ($this->properties as $name => $type) {
573: if (ConstantArrayType::isValidIdentifier((string) $name)) {
574: $keyNode = new IdentifierTypeNode((string) $name);
575: } else {
576: $keyPhpDocNode = (new ConstantStringType((string) $name))->toPhpDocNode();
577: if (!$keyPhpDocNode instanceof ConstTypeNode) {
578: continue;
579: }
580:
581: /** @var ConstExprStringNode $keyNode */
582: $keyNode = $keyPhpDocNode->constExpr;
583: }
584: $items[] = new ObjectShapeItemNode(
585: $keyNode,
586: in_array($name, $this->optionalProperties, true),
587: $type->toPhpDocNode(),
588: );
589: }
590:
591: return new ObjectShapeNode($items);
592: }
593:
594: public function toNativePhpTypeNode(NativeTypePosition $position)
595: {
596: return $position->isObjectAllowed() ? new Identifier('object') : null;
597: }
598:
599: public function hasTemplateOrLateResolvableType(): bool
600: {
601: foreach ($this->properties as $property) {
602: if (!$property->hasTemplateOrLateResolvableType()) {
603: continue;
604: }
605:
606: return true;
607: }
608:
609: return false;
610: }
611:
612: public function toValueSet(): ValueSet
613: {
614: return ValueSet::createObjects($this);
615: }
616:
617: }
618: