-
Notifications
You must be signed in to change notification settings - Fork 506
/
Copy pathConstantStringType.php
571 lines (466 loc) · 15.3 KB
/
ConstantStringType.php
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
<?php declare(strict_types = 1);
namespace PHPStan\Type\Constant;
use Nette\Utils\RegexpException;
use Nette\Utils\Strings;
use PhpParser\Node\Name;
use PHPStan\Analyser\OutOfClassScope;
use PHPStan\Php\PhpVersion;
use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode;
use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\Reflection\Callables\FunctionCallableVariant;
use PHPStan\Reflection\ClassConstantReflection;
use PHPStan\Reflection\ClassMemberAccessAnswerer;
use PHPStan\Reflection\InaccessibleMethod;
use PHPStan\Reflection\PhpVersionStaticAccessor;
use PHPStan\Reflection\ReflectionProviderStaticAccessor;
use PHPStan\Reflection\TrivialParametersAcceptor;
use PHPStan\ShouldNotHappenException;
use PHPStan\TrinaryLogic;
use PHPStan\Type\Accessory\AccessoryLiteralStringType;
use PHPStan\Type\Accessory\AccessoryLowercaseStringType;
use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
use PHPStan\Type\Accessory\AccessoryNumericStringType;
use PHPStan\Type\Accessory\AccessoryUppercaseStringType;
use PHPStan\Type\ClassStringType;
use PHPStan\Type\CompoundType;
use PHPStan\Type\ConstantScalarType;
use PHPStan\Type\ErrorType;
use PHPStan\Type\GeneralizePrecision;
use PHPStan\Type\Generic\GenericClassStringType;
use PHPStan\Type\Generic\TemplateType;
use PHPStan\Type\IntegerRangeType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\IsSuperTypeOfResult;
use PHPStan\Type\MixedType;
use PHPStan\Type\NullType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\StaticType;
use PHPStan\Type\StringType;
use PHPStan\Type\Traits\ConstantScalarTypeTrait;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\VerbosityLevel;
use function addcslashes;
use function in_array;
use function is_float;
use function is_int;
use function is_numeric;
use function key;
use function strlen;
use function strtolower;
use function strtoupper;
use function substr;
use function substr_count;
/** @api */
class ConstantStringType extends StringType implements ConstantScalarType
{
private const DESCRIBE_LIMIT = 20;
use ConstantScalarTypeTrait;
use ConstantScalarToBooleanTrait;
private ?ObjectType $objectType = null;
private ?Type $arrayKeyType = null;
/** @api */
public function __construct(private string $value, private bool $isClassString = false)
{
parent::__construct();
}
public function getValue(): string
{
return $this->value;
}
public function getConstantStrings(): array
{
return [$this];
}
public function isClassString(): TrinaryLogic
{
if ($this->isClassString) {
return TrinaryLogic::createYes();
}
$reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
return TrinaryLogic::createFromBoolean($reflectionProvider->hasClass($this->value));
}
public function getClassStringObjectType(): Type
{
if ($this->isClassString()->yes()) {
return new ObjectType($this->value);
}
return new ErrorType();
}
public function getObjectTypeOrClassStringObjectType(): Type
{
return $this->getClassStringObjectType();
}
public function describe(VerbosityLevel $level): string
{
return $level->handle(
static fn (): string => 'string',
function (): string {
$value = $this->value;
if (!$this->isClassString) {
try {
$value = Strings::truncate($value, self::DESCRIBE_LIMIT);
} catch (RegexpException) {
$value = substr($value, 0, self::DESCRIBE_LIMIT) . "\u{2026}";
}
}
return self::export($value);
},
fn (): string => self::export($this->value),
);
}
private function export(string $value): string
{
$escapedValue = addcslashes($value, "\0..\37");
if ($escapedValue !== $value) {
return '"' . addcslashes($value, "\0..\37\\\"") . '"';
}
return "'" . addcslashes($value, '\\\'') . "'";
}
public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
{
if ($type instanceof GenericClassStringType) {
$genericType = $type->getGenericType();
if ($genericType instanceof MixedType) {
return IsSuperTypeOfResult::createMaybe();
}
if ($genericType instanceof StaticType) {
$genericType = $genericType->getStaticObjectType();
}
// We are transforming constant class-string to ObjectType. But we need to filter out
// an uncertainty originating in possible ObjectType's class subtypes.
$objectType = $this->getObjectType();
// Do not use TemplateType's isSuperTypeOf handling directly because it takes ObjectType
// uncertainty into account.
if ($genericType instanceof TemplateType) {
$isSuperType = $genericType->getBound()->isSuperTypeOf($objectType);
} else {
$isSuperType = $genericType->isSuperTypeOf($objectType);
}
// Explicitly handle the uncertainty for Yes & Maybe.
if ($isSuperType->yes()) {
return IsSuperTypeOfResult::createMaybe();
}
return IsSuperTypeOfResult::createNo();
}
if ($type instanceof ClassStringType) {
return $this->isClassString()->yes() ? IsSuperTypeOfResult::createMaybe() : IsSuperTypeOfResult::createNo();
}
if ($type instanceof self) {
return $this->value === $type->value ? IsSuperTypeOfResult::createYes() : IsSuperTypeOfResult::createNo();
}
if ($type instanceof parent) {
return IsSuperTypeOfResult::createMaybe();
}
if ($type instanceof CompoundType) {
return $type->isSubTypeOf($this);
}
return IsSuperTypeOfResult::createNo();
}
public function isCallable(): TrinaryLogic
{
if ($this->value === '') {
return TrinaryLogic::createNo();
}
$reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
// 'my_function'
if ($reflectionProvider->hasFunction(new Name($this->value), null)) {
return TrinaryLogic::createYes();
}
// 'MyClass::myStaticFunction'
$matches = Strings::match($this->value, '#^([a-zA-Z_\\x7f-\\xff\\\\][a-zA-Z0-9_\\x7f-\\xff\\\\]*)::([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)\z#');
if ($matches !== null) {
if (!$reflectionProvider->hasClass($matches[1])) {
return TrinaryLogic::createMaybe();
}
$phpVersion = PhpVersionStaticAccessor::getInstance();
$classRef = $reflectionProvider->getClass($matches[1]);
if ($classRef->hasMethod($matches[2])) {
$method = $classRef->getMethod($matches[2], new OutOfClassScope());
if (
!$phpVersion->supportsCallableInstanceMethods()
&& !$method->isStatic()
) {
return TrinaryLogic::createNo();
}
return TrinaryLogic::createYes();
}
if (!$classRef->isFinalByKeyword()) {
return TrinaryLogic::createMaybe();
}
return TrinaryLogic::createNo();
}
return TrinaryLogic::createNo();
}
public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
{
if ($this->value === '') {
return [];
}
$reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
// 'my_function'
$functionName = new Name($this->value);
if ($reflectionProvider->hasFunction($functionName, null)) {
$function = $reflectionProvider->getFunction($functionName, null);
return FunctionCallableVariant::createFromVariants($function, $function->getVariants());
}
// 'MyClass::myStaticFunction'
$matches = Strings::match($this->value, '#^([a-zA-Z_\\x7f-\\xff\\\\][a-zA-Z0-9_\\x7f-\\xff\\\\]*)::([a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)\z#');
if ($matches !== null) {
if (!$reflectionProvider->hasClass($matches[1])) {
return [new TrivialParametersAcceptor()];
}
$classReflection = $reflectionProvider->getClass($matches[1]);
if ($classReflection->hasMethod($matches[2])) {
$method = $classReflection->getMethod($matches[2], $scope);
if (!$scope->canCallMethod($method)) {
return [new InaccessibleMethod($method)];
}
return FunctionCallableVariant::createFromVariants($method, $method->getVariants());
}
if (!$classReflection->isFinalByKeyword()) {
return [new TrivialParametersAcceptor()];
}
}
throw new ShouldNotHappenException();
}
public function toNumber(): Type
{
if (is_numeric($this->value)) {
$value = $this->value;
$value = +$value;
if (is_float($value)) {
return new ConstantFloatType($value);
}
return new ConstantIntegerType($value);
}
return new ErrorType();
}
public function toAbsoluteNumber(): Type
{
return $this->toNumber()->toAbsoluteNumber();
}
public function toInteger(): Type
{
return new ConstantIntegerType((int) $this->value);
}
public function toFloat(): Type
{
return new ConstantFloatType((float) $this->value);
}
public function toArrayKey(): Type
{
if ($this->arrayKeyType !== null) {
return $this->arrayKeyType;
}
/** @var int|string $offsetValue */
$offsetValue = key([$this->value => null]);
return $this->arrayKeyType = is_int($offsetValue) ? new ConstantIntegerType($offsetValue) : new ConstantStringType($offsetValue);
}
public function isString(): TrinaryLogic
{
return TrinaryLogic::createYes();
}
public function isNumericString(): TrinaryLogic
{
return TrinaryLogic::createFromBoolean(is_numeric($this->getValue()));
}
public function isNonEmptyString(): TrinaryLogic
{
return TrinaryLogic::createFromBoolean($this->getValue() !== '');
}
public function isNonFalsyString(): TrinaryLogic
{
return TrinaryLogic::createFromBoolean(!in_array($this->getValue(), ['', '0'], true));
}
public function isLiteralString(): TrinaryLogic
{
return TrinaryLogic::createYes();
}
public function isLowercaseString(): TrinaryLogic
{
return TrinaryLogic::createFromBoolean(strtolower($this->value) === $this->value);
}
public function isUppercaseString(): TrinaryLogic
{
return TrinaryLogic::createFromBoolean(strtoupper($this->value) === $this->value);
}
public function hasOffsetValueType(Type $offsetType): TrinaryLogic
{
if ($offsetType->isInteger()->yes()) {
$strlen = strlen($this->value);
$strLenType = IntegerRangeType::fromInterval(-$strlen, $strlen - 1);
return $strLenType->isSuperTypeOf($offsetType)->result;
}
return parent::hasOffsetValueType($offsetType);
}
public function getOffsetValueType(Type $offsetType): Type
{
if ($offsetType->isInteger()->yes()) {
$strlen = strlen($this->value);
$strLenType = IntegerRangeType::fromInterval(-$strlen, $strlen - 1);
if ($offsetType instanceof ConstantIntegerType) {
if ($strLenType->isSuperTypeOf($offsetType)->yes()) {
return new self($this->value[$offsetType->getValue()]);
}
return new ErrorType();
}
$intersected = TypeCombinator::intersect($strLenType, $offsetType);
if ($intersected instanceof IntegerRangeType) {
$finiteTypes = $intersected->getFiniteTypes();
if ($finiteTypes === []) {
return parent::getOffsetValueType($offsetType);
}
$chars = [];
foreach ($finiteTypes as $constantInteger) {
$chars[] = new self($this->value[$constantInteger->getValue()]);
}
if (!$strLenType->isSuperTypeOf($offsetType)->yes()) {
$chars[] = new self('');
}
return TypeCombinator::union(...$chars);
}
}
return parent::getOffsetValueType($offsetType);
}
public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
{
$valueStringType = $valueType->toString();
if ($valueStringType instanceof ErrorType) {
return new ErrorType();
}
if (
$offsetType instanceof ConstantIntegerType
&& $valueStringType instanceof ConstantStringType
) {
$value = $this->value;
$offsetValue = $offsetType->getValue();
if ($offsetValue < 0) {
return new ErrorType();
}
$stringValue = $valueStringType->getValue();
if (strlen($stringValue) !== 1) {
return new ErrorType();
}
$value[$offsetValue] = $stringValue;
return new self($value);
}
return parent::setOffsetValueType($offsetType, $valueType);
}
public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
{
return parent::setOffsetValueType($offsetType, $valueType);
}
public function append(self $otherString): self
{
return new self($this->getValue() . $otherString->getValue());
}
public function generalize(GeneralizePrecision $precision): Type
{
if ($this->isClassString) {
if ($precision->isMoreSpecific()) {
return new ClassStringType();
}
return new StringType();
}
if ($this->getValue() !== '' && $precision->isMoreSpecific()) {
$accessories = [
new StringType(),
new AccessoryLiteralStringType(),
];
if (is_numeric($this->getValue())) {
$accessories[] = new AccessoryNumericStringType();
}
if ($this->getValue() !== '0') {
$accessories[] = new AccessoryNonFalsyStringType();
} else {
$accessories[] = new AccessoryNonEmptyStringType();
}
if (strtolower($this->getValue()) === $this->getValue()) {
$accessories[] = new AccessoryLowercaseStringType();
}
if (strtoupper($this->getValue()) === $this->getValue()) {
$accessories[] = new AccessoryUppercaseStringType();
}
return new IntersectionType($accessories);
}
if ($precision->isMoreSpecific()) {
return new IntersectionType([
new StringType(),
new AccessoryLiteralStringType(),
]);
}
return new StringType();
}
public function getSmallerType(PhpVersion $phpVersion): Type
{
$subtractedTypes = [
new ConstantBooleanType(true),
IntegerRangeType::createAllGreaterThanOrEqualTo((float) $this->value),
];
if ($this->value === '') {
$subtractedTypes[] = new NullType();
$subtractedTypes[] = new StringType();
}
if (!(bool) $this->value) {
$subtractedTypes[] = new ConstantBooleanType(false);
}
return TypeCombinator::remove(new MixedType(), TypeCombinator::union(...$subtractedTypes));
}
public function getSmallerOrEqualType(PhpVersion $phpVersion): Type
{
$subtractedTypes = [
IntegerRangeType::createAllGreaterThan((float) $this->value),
];
if (!(bool) $this->value) {
$subtractedTypes[] = new ConstantBooleanType(true);
}
return TypeCombinator::remove(new MixedType(), TypeCombinator::union(...$subtractedTypes));
}
public function getGreaterType(PhpVersion $phpVersion): Type
{
$subtractedTypes = [
new ConstantBooleanType(false),
IntegerRangeType::createAllSmallerThanOrEqualTo((float) $this->value),
];
if ((bool) $this->value) {
$subtractedTypes[] = new ConstantBooleanType(true);
}
return TypeCombinator::remove(new MixedType(), TypeCombinator::union(...$subtractedTypes));
}
public function getGreaterOrEqualType(PhpVersion $phpVersion): Type
{
$subtractedTypes = [
IntegerRangeType::createAllSmallerThan((float) $this->value),
];
if ((bool) $this->value) {
$subtractedTypes[] = new ConstantBooleanType(false);
}
return TypeCombinator::remove(new MixedType(), TypeCombinator::union(...$subtractedTypes));
}
public function canAccessConstants(): TrinaryLogic
{
return $this->isClassString();
}
public function hasConstant(string $constantName): TrinaryLogic
{
return $this->getObjectType()->hasConstant($constantName);
}
public function getConstant(string $constantName): ClassConstantReflection
{
return $this->getObjectType()->getConstant($constantName);
}
private function getObjectType(): ObjectType
{
return $this->objectType ??= new ObjectType($this->value);
}
public function toPhpDocNode(): TypeNode
{
if (substr_count($this->value, "\n") > 0) {
return $this->generalize(GeneralizePrecision::moreSpecific())->toPhpDocNode();
}
return new ConstTypeNode(new ConstExprStringNode($this->value, ConstExprStringNode::SINGLE_QUOTED));
}
}