1: <?php declare(strict_types = 1);
2:
3: namespace PHPStan\Type\Constant;
4:
5: use Nette\Utils\RegexpException;
6: use Nette\Utils\Strings;
7: use PhpParser\Node\Name;
8: use PHPStan\Analyser\OutOfClassScope;
9: use PHPStan\Php\PhpVersion;
10: use PHPStan\PhpDocParser\Ast\ConstExpr\ConstExprStringNode;
11: use PHPStan\PhpDocParser\Ast\Type\ConstTypeNode;
12: use PHPStan\PhpDocParser\Ast\Type\TypeNode;
13: use PHPStan\Reflection\Callables\FunctionCallableVariant;
14: use PHPStan\Reflection\ClassConstantReflection;
15: use PHPStan\Reflection\ClassMemberAccessAnswerer;
16: use PHPStan\Reflection\InaccessibleMethod;
17: use PHPStan\Reflection\PhpVersionStaticAccessor;
18: use PHPStan\Reflection\ReflectionProviderStaticAccessor;
19: use PHPStan\Reflection\TrivialParametersAcceptor;
20: use PHPStan\ShouldNotHappenException;
21: use PHPStan\TrinaryLogic;
22: use PHPStan\Turbo\ShadowedByTurboExtension;
23: use PHPStan\Type\Accessory\AccessoryLiteralStringType;
24: use PHPStan\Type\Accessory\AccessoryLowercaseStringType;
25: use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
26: use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
27: use PHPStan\Type\Accessory\AccessoryNumericStringType;
28: use PHPStan\Type\Accessory\AccessoryUppercaseStringType;
29: use PHPStan\Type\ClassNameToObjectTypeResult;
30: use PHPStan\Type\ClassStringType;
31: use PHPStan\Type\CompoundType;
32: use PHPStan\Type\ConstantScalarType;
33: use PHPStan\Type\ErrorType;
34: use PHPStan\Type\GeneralizePrecision;
35: use PHPStan\Type\Generic\GenericClassStringType;
36: use PHPStan\Type\Generic\TemplateType;
37: use PHPStan\Type\InstanceofDeprecated;
38: use PHPStan\Type\IntegerRangeType;
39: use PHPStan\Type\IntersectionType;
40: use PHPStan\Type\IsSuperTypeOfResult;
41: use PHPStan\Type\MixedType;
42: use PHPStan\Type\NeverType;
43: use PHPStan\Type\NullType;
44: use PHPStan\Type\ObjectType;
45: use PHPStan\Type\StaticType;
46: use PHPStan\Type\StringType;
47: use PHPStan\Type\Traits\ConstantScalarTypeTrait;
48: use PHPStan\Type\Type;
49: use PHPStan\Type\TypeCombinator;
50: use PHPStan\Type\UnionType;
51: use PHPStan\Type\ValueSet;
52: use PHPStan\Type\VerbosityLevel;
53: use function addcslashes;
54: use function array_unique;
55: use function array_values;
56: use function in_array;
57: use function is_float;
58: use function is_int;
59: use function is_numeric;
60: use function key;
61: use function strlen;
62: use function strtolower;
63: use function strtoupper;
64: use function substr;
65: use function substr_count;
66:
67: /** @api */
68: #[InstanceofDeprecated(insteadUse: 'Type::getConstantStrings()')]
69: #[ShadowedByTurboExtension(implementation: __DIR__ . '/../../../turbo-ext/src/ConstantStringType.cpp')]
70: class ConstantStringType extends StringType implements ConstantScalarType
71: {
72:
73: private const DESCRIBE_LIMIT = 20;
74:
75: use ConstantScalarTypeTrait;
76: use ConstantScalarToBooleanTrait;
77:
78: private ?ObjectType $objectType = null;
79:
80: private ?Type $arrayKeyType = null;
81:
82: /** @var array<int, string> */
83: private array $cachedDescriptions = [];
84:
85: /** @api */
86: public function __construct(private string $value, private bool $isClassString = false)
87: {
88: parent::__construct();
89: }
90:
91: public function getValue(): string
92: {
93: return $this->value;
94: }
95:
96: public function getConstantStrings(): array
97: {
98: return [$this];
99: }
100:
101: public function isClassString(): TrinaryLogic
102: {
103: if ($this->isClassString) {
104: return TrinaryLogic::createYes();
105: }
106:
107: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
108:
109: return TrinaryLogic::createFromBoolean($reflectionProvider->hasClass($this->value));
110: }
111:
112: public function getClassStringObjectType(): Type
113: {
114: if ($this->isClassString()->yes()) {
115: return new ObjectType($this->value);
116: }
117:
118: return new ErrorType();
119: }
120:
121: public function getObjectTypeOrClassStringObjectType(): Type
122: {
123: return $this->getClassStringObjectType();
124: }
125:
126: public function describe(VerbosityLevel $level): string
127: {
128: $levelValue = $level->getLevelValue();
129:
130: if (isset($this->cachedDescriptions[$levelValue])) {
131: return $this->cachedDescriptions[$levelValue];
132: }
133:
134: // what VerbosityLevel::handle() would pick, without creating its callbacks
135: if ($level->isTypeOnly()) {
136: return 'string';
137: }
138:
139: if ($level->isValue()) {
140: $value = $this->value;
141:
142: if (!$this->isClassString) {
143: try {
144: $value = Strings::truncate($value, self::DESCRIBE_LIMIT);
145: } catch (RegexpException) {
146: $value = substr($value, 0, self::DESCRIBE_LIMIT) . "\u{2026}";
147: }
148: }
149:
150: return $this->cachedDescriptions[$levelValue] = self::export($value);
151: }
152:
153: return $this->cachedDescriptions[$levelValue] = self::export($this->value);
154: }
155:
156: private function export(string $value): string
157: {
158: $escapedValue = addcslashes($value, "\0..\37");
159: if ($escapedValue !== $value) {
160: return '"' . addcslashes($value, "\0..\37\\\"") . '"';
161: }
162:
163: return "'" . addcslashes($value, '\\\'') . "'";
164: }
165:
166: public function isSuperTypeOf(Type $type): IsSuperTypeOfResult
167: {
168: if ($type instanceof GenericClassStringType) {
169: $genericType = $type->getGenericType();
170: if ($genericType instanceof MixedType) {
171: return IsSuperTypeOfResult::createMaybe();
172: }
173: if ($genericType instanceof StaticType) {
174: $genericType = $genericType->getStaticObjectType();
175: }
176:
177: // We are transforming constant class-string to ObjectType. But we need to filter out
178: // an uncertainty originating in possible ObjectType's class subtypes.
179: $objectType = $this->getObjectType();
180:
181: // Do not use TemplateType's isSuperTypeOf handling directly because it takes ObjectType
182: // uncertainty into account.
183: if ($genericType instanceof TemplateType) {
184: $isSuperType = $genericType->getBound()->isSuperTypeOf($objectType);
185: } else {
186: $isSuperType = $genericType->isSuperTypeOf($objectType);
187: }
188:
189: // Explicitly handle the uncertainty for Yes & Maybe.
190: if ($isSuperType->yes()) {
191: return IsSuperTypeOfResult::createMaybe();
192: }
193: return IsSuperTypeOfResult::createNo();
194: }
195: if ($type instanceof ClassStringType) {
196: return $this->isClassString()->yes() ? IsSuperTypeOfResult::createMaybe() : IsSuperTypeOfResult::createNo();
197: }
198:
199: if ($type instanceof self) {
200: return $this->value === $type->value ? IsSuperTypeOfResult::createYes() : IsSuperTypeOfResult::createNo();
201: }
202:
203: if ($type instanceof parent) {
204: return IsSuperTypeOfResult::createMaybe();
205: }
206:
207: if ($type instanceof CompoundType) {
208: return $type->isSubTypeOf($this);
209: }
210:
211: return IsSuperTypeOfResult::createNo();
212: }
213:
214: public function isCallable(): TrinaryLogic
215: {
216: if ($this->value === '') {
217: return TrinaryLogic::createNo();
218: }
219:
220: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
221:
222: // 'my_function'
223: if ($reflectionProvider->hasFunction(new Name($this->value), null)) {
224: return TrinaryLogic::createYes();
225: }
226:
227: // 'MyClass::myStaticFunction'
228: $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#');
229: if ($matches !== null) {
230: if (!$reflectionProvider->hasClass($matches[1])) {
231: return TrinaryLogic::createMaybe();
232: }
233:
234: $classRef = $reflectionProvider->getClass($matches[1]);
235: if ($classRef->hasMethod($matches[2])) {
236: $phpVersion = PhpVersionStaticAccessor::getInstance();
237: if (!$phpVersion->supportsCallableInstanceMethods()) {
238: $method = $classRef->getMethod($matches[2], new OutOfClassScope());
239:
240: if (!$method->isStatic()) {
241: return TrinaryLogic::createNo();
242: }
243: }
244:
245: return TrinaryLogic::createYes();
246: }
247:
248: if (!$classRef->isFinalByKeyword()) {
249: return TrinaryLogic::createMaybe();
250: }
251:
252: return TrinaryLogic::createNo();
253: }
254:
255: return TrinaryLogic::createNo();
256: }
257:
258: public function getCallableParametersAcceptors(ClassMemberAccessAnswerer $scope): array
259: {
260: if ($this->value === '') {
261: return [];
262: }
263:
264: $reflectionProvider = ReflectionProviderStaticAccessor::getInstance();
265:
266: // 'my_function'
267: $functionName = new Name($this->value);
268: if ($reflectionProvider->hasFunction($functionName, null)) {
269: $function = $reflectionProvider->getFunction($functionName, null);
270: return FunctionCallableVariant::createFromVariants($function, $function->getVariants());
271: }
272:
273: // 'MyClass::myStaticFunction'
274: $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#');
275: if ($matches !== null) {
276: if (!$reflectionProvider->hasClass($matches[1])) {
277: return [new TrivialParametersAcceptor()];
278: }
279:
280: $classReflection = $reflectionProvider->getClass($matches[1]);
281: if ($classReflection->hasMethod($matches[2])) {
282: $method = $classReflection->getMethod($matches[2], $scope);
283: if (!$scope->canCallMethod($method)) {
284: return [new InaccessibleMethod($method)];
285: }
286:
287: return FunctionCallableVariant::createFromVariants($method, $method->getVariants());
288: }
289:
290: if (!$classReflection->isFinalByKeyword()) {
291: return [new TrivialParametersAcceptor()];
292: }
293: }
294:
295: throw new ShouldNotHappenException();
296: }
297:
298: public function toNumber(): Type
299: {
300: if (is_numeric($this->value)) {
301: $value = $this->value;
302: $value = +$value;
303: if (is_float($value)) {
304: return new ConstantFloatType($value);
305: }
306:
307: return new ConstantIntegerType($value);
308: }
309:
310: return new ErrorType();
311: }
312:
313: public function toBitwiseNotType(): Type
314: {
315: return new ConstantStringType(~$this->value);
316: }
317:
318: public function toObjectTypeForInstanceofCheck(): ClassNameToObjectTypeResult
319: {
320: return new ClassNameToObjectTypeResult(new ObjectType($this->value), false);
321: }
322:
323: public function toObjectTypeForIsACheck(Type $objectOrClassType, bool $allowString, bool $allowSameClass): ClassNameToObjectTypeResult
324: {
325: $objectOrClassTypeClassNames = $objectOrClassType->getObjectClassNames();
326: if ($allowString) {
327: foreach ($objectOrClassType->getConstantStrings() as $constantString) {
328: $objectOrClassTypeClassNames[] = $constantString->getValue();
329: }
330: $objectOrClassTypeClassNames = array_values(array_unique($objectOrClassTypeClassNames));
331: }
332:
333: $uncertainty = false;
334: if (!$allowSameClass) {
335: if ($objectOrClassTypeClassNames === [$this->value]) {
336: $isSameClass = true;
337: foreach ($objectOrClassType->getObjectClassReflections() as $classReflection) {
338: if (!$classReflection->isFinal()) {
339: $isSameClass = false;
340: break;
341: }
342: }
343:
344: if ($isSameClass) {
345: return new ClassNameToObjectTypeResult(new NeverType(), false);
346: }
347: }
348:
349: if (
350: // For object, as soon as the exact same type is provided
351: // in the list we cannot be sure of the result
352: in_array($this->value, $objectOrClassTypeClassNames, true)
353: // This also occurs for generic class string
354: || ($allowString && $objectOrClassTypeClassNames === [] && $objectOrClassType->isSuperTypeOf($this)->yes())
355: ) {
356: $uncertainty = true;
357: }
358: }
359:
360: if ($allowString) {
361: return new ClassNameToObjectTypeResult(
362: new UnionType([
363: new ObjectType($this->value),
364: new GenericClassStringType(new ObjectType($this->value)),
365: ]),
366: $uncertainty,
367: );
368: }
369:
370: return new ClassNameToObjectTypeResult(new ObjectType($this->value), $uncertainty);
371: }
372:
373: public function toAbsoluteNumber(): Type
374: {
375: return $this->toNumber()->toAbsoluteNumber();
376: }
377:
378: public function toInteger(): Type
379: {
380: return new ConstantIntegerType((int) $this->value);
381: }
382:
383: public function toFloat(): Type
384: {
385: return new ConstantFloatType((float) $this->value);
386: }
387:
388: public function toArrayKey(): Type
389: {
390: if ($this->arrayKeyType !== null) {
391: return $this->arrayKeyType;
392: }
393:
394: /** @var int|string $offsetValue */
395: $offsetValue = key([$this->value => null]);
396:
397: if ($offsetValue === $this->value) {
398: return $this;
399: }
400:
401: return $this->arrayKeyType = is_int($offsetValue) ? new ConstantIntegerType($offsetValue) : new ConstantStringType($offsetValue);
402: }
403:
404: public function isString(): TrinaryLogic
405: {
406: return TrinaryLogic::createYes();
407: }
408:
409: public function isNumericString(): TrinaryLogic
410: {
411: return TrinaryLogic::createFromBoolean(is_numeric($this->getValue()));
412: }
413:
414: public function isDecimalIntegerString(): TrinaryLogic
415: {
416: return TrinaryLogic::createFromBoolean((string) (int) $this->value === $this->value);
417: }
418:
419: public function isNonEmptyString(): TrinaryLogic
420: {
421: return TrinaryLogic::createFromBoolean($this->getValue() !== '');
422: }
423:
424: public function isNonFalsyString(): TrinaryLogic
425: {
426: return TrinaryLogic::createFromBoolean(!in_array($this->getValue(), ['', '0'], true));
427: }
428:
429: public function isLiteralString(): TrinaryLogic
430: {
431: return TrinaryLogic::createYes();
432: }
433:
434: /** A constant is a value of its cell, not the whole cell: StringRefinement::ofConstant(). */
435: public function getStringRefinement(): ?int
436: {
437: return null;
438: }
439:
440: public function isLowercaseString(): TrinaryLogic
441: {
442: return TrinaryLogic::createFromBoolean(strtolower($this->value) === $this->value);
443: }
444:
445: public function isUppercaseString(): TrinaryLogic
446: {
447: return TrinaryLogic::createFromBoolean(strtoupper($this->value) === $this->value);
448: }
449:
450: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
451: {
452: if ($offsetType->isInteger()->yes()) {
453: $strlen = strlen($this->value);
454: $strLenType = IntegerRangeType::fromInterval(-$strlen, $strlen - 1);
455: return $strLenType->isSuperTypeOf($offsetType)->result;
456: }
457:
458: return parent::hasOffsetValueType($offsetType);
459: }
460:
461: public function getOffsetValueType(Type $offsetType): Type
462: {
463: if ($offsetType->isInteger()->yes()) {
464: $strlen = strlen($this->value);
465: $strLenType = IntegerRangeType::fromInterval(-$strlen, $strlen - 1);
466:
467: $isInString = $strLenType->isSuperTypeOf($offsetType);
468: if ($isInString->no()) {
469: return new ErrorType();
470: }
471:
472: /** @var list<ConstantIntegerType> $finiteTypes */
473: $finiteTypes = TypeCombinator::intersect($strLenType, $offsetType)->getFiniteTypes();
474: if ($finiteTypes === []) {
475: return parent::getOffsetValueType($offsetType);
476: }
477:
478: $chars = [];
479: foreach ($finiteTypes as $constantInteger) {
480: $chars[] = new self($this->value[$constantInteger->getValue()]);
481: }
482: if (!$isInString->yes()) {
483: $chars[] = new self('');
484: }
485:
486: return TypeCombinator::union(...$chars);
487: }
488:
489: return parent::getOffsetValueType($offsetType);
490: }
491:
492: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
493: {
494: $valueStringType = $valueType->toString();
495: if ($valueStringType instanceof ErrorType) {
496: return new ErrorType();
497: }
498: if (
499: $offsetType instanceof ConstantIntegerType
500: && $valueStringType instanceof ConstantStringType
501: ) {
502: $value = $this->value;
503: $offsetValue = $offsetType->getValue();
504: if ($offsetValue < 0) {
505: return new ErrorType();
506: }
507: $stringValue = $valueStringType->getValue();
508: if (strlen($stringValue) !== 1) {
509: return new ErrorType();
510: }
511: $value[$offsetValue] = $stringValue;
512:
513: return new self($value);
514: }
515:
516: return parent::setOffsetValueType($offsetType, $valueType);
517: }
518:
519: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
520: {
521: return parent::setOffsetValueType($offsetType, $valueType);
522: }
523:
524: public function append(self $otherString): self
525: {
526: return new self($this->getValue() . $otherString->getValue());
527: }
528:
529: public function generalize(GeneralizePrecision $precision): Type
530: {
531: if ($this->isClassString) {
532: if ($precision->isMoreSpecific()) {
533: return new ClassStringType();
534: }
535:
536: return new StringType();
537: }
538:
539: if ($this->getValue() !== '' && $precision->isMoreSpecific()) {
540: $accessories = [
541: new StringType(),
542: new AccessoryLiteralStringType(),
543: ];
544:
545: if (is_numeric($this->getValue())) {
546: $accessories[] = new AccessoryNumericStringType();
547: }
548:
549: if ($this->getValue() !== '0') {
550: $accessories[] = new AccessoryNonFalsyStringType();
551: } else {
552: $accessories[] = new AccessoryNonEmptyStringType();
553: }
554:
555: if (strtolower($this->getValue()) === $this->getValue()) {
556: $accessories[] = new AccessoryLowercaseStringType();
557: }
558:
559: if (strtoupper($this->getValue()) === $this->getValue()) {
560: $accessories[] = new AccessoryUppercaseStringType();
561: }
562:
563: return new IntersectionType($accessories);
564: }
565:
566: if ($precision->isMoreSpecific()) {
567: return new IntersectionType([
568: new StringType(),
569: new AccessoryLiteralStringType(),
570: ]);
571: }
572:
573: return new StringType();
574: }
575:
576: public function getSmallerType(PhpVersion $phpVersion): Type
577: {
578: $subtractedTypes = [
579: new ConstantBooleanType(true),
580: IntegerRangeType::createAllGreaterThanOrEqualTo((float) $this->value),
581: ];
582:
583: if ($this->value === '') {
584: $subtractedTypes[] = new NullType();
585: $subtractedTypes[] = new StringType();
586: }
587:
588: if (!(bool) $this->value) {
589: $subtractedTypes[] = new ConstantBooleanType(false);
590: }
591:
592: return TypeCombinator::remove(new MixedType(), TypeCombinator::union(...$subtractedTypes));
593: }
594:
595: public function getSmallerOrEqualType(PhpVersion $phpVersion): Type
596: {
597: $subtractedTypes = [
598: IntegerRangeType::createAllGreaterThan((float) $this->value),
599: ];
600:
601: if (!(bool) $this->value) {
602: $subtractedTypes[] = new ConstantBooleanType(true);
603: }
604:
605: return TypeCombinator::remove(new MixedType(), TypeCombinator::union(...$subtractedTypes));
606: }
607:
608: public function getGreaterType(PhpVersion $phpVersion): Type
609: {
610: $subtractedTypes = [
611: new ConstantBooleanType(false),
612: IntegerRangeType::createAllSmallerThanOrEqualTo((float) $this->value),
613: ];
614:
615: if ((bool) $this->value) {
616: $subtractedTypes[] = new ConstantBooleanType(true);
617: }
618:
619: return TypeCombinator::remove(new MixedType(), TypeCombinator::union(...$subtractedTypes));
620: }
621:
622: public function getGreaterOrEqualType(PhpVersion $phpVersion): Type
623: {
624: $subtractedTypes = [
625: IntegerRangeType::createAllSmallerThan((float) $this->value),
626: ];
627:
628: if ((bool) $this->value) {
629: $subtractedTypes[] = new ConstantBooleanType(false);
630: }
631:
632: return TypeCombinator::remove(new MixedType(), TypeCombinator::union(...$subtractedTypes));
633: }
634:
635: public function canAccessConstants(): TrinaryLogic
636: {
637: return $this->isClassString();
638: }
639:
640: public function hasConstant(string $constantName): TrinaryLogic
641: {
642: return $this->getObjectType()->hasConstant($constantName);
643: }
644:
645: public function getConstant(string $constantName): ClassConstantReflection
646: {
647: return $this->getObjectType()->getConstant($constantName);
648: }
649:
650: private function getObjectType(): ObjectType
651: {
652: return $this->objectType ??= new ObjectType($this->value);
653: }
654:
655: public function toPhpDocNode(): TypeNode
656: {
657: if (substr_count($this->value, "\n") > 0) {
658: return $this->generalize(GeneralizePrecision::moreSpecific())->toPhpDocNode();
659: }
660:
661: return new ConstTypeNode(new ConstExprStringNode($this->value, ConstExprStringNode::SINGLE_QUOTED));
662: }
663:
664: public function toValueSet(): ValueSet
665: {
666: return ValueSet::createConstantString($this);
667: }
668:
669: }
670: