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