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: public function isLowercaseString(): TrinaryLogic
435: {
436: return TrinaryLogic::createFromBoolean(strtolower($this->value) === $this->value);
437: }
438:
439: public function isUppercaseString(): TrinaryLogic
440: {
441: return TrinaryLogic::createFromBoolean(strtoupper($this->value) === $this->value);
442: }
443:
444: public function hasOffsetValueType(Type $offsetType): TrinaryLogic
445: {
446: if ($offsetType->isInteger()->yes()) {
447: $strlen = strlen($this->value);
448: $strLenType = IntegerRangeType::fromInterval(-$strlen, $strlen - 1);
449: return $strLenType->isSuperTypeOf($offsetType)->result;
450: }
451:
452: return parent::hasOffsetValueType($offsetType);
453: }
454:
455: public function getOffsetValueType(Type $offsetType): Type
456: {
457: if ($offsetType->isInteger()->yes()) {
458: $strlen = strlen($this->value);
459: $strLenType = IntegerRangeType::fromInterval(-$strlen, $strlen - 1);
460:
461: if ($offsetType instanceof ConstantIntegerType) {
462: if ($strLenType->isSuperTypeOf($offsetType)->yes()) {
463: return new self($this->value[$offsetType->getValue()]);
464: }
465:
466: return new ErrorType();
467: }
468:
469: $intersected = TypeCombinator::intersect($strLenType, $offsetType);
470: if ($intersected instanceof IntegerRangeType) {
471: $finiteTypes = $intersected->getFiniteTypes();
472: if ($finiteTypes === []) {
473: return parent::getOffsetValueType($offsetType);
474: }
475:
476: $chars = [];
477: foreach ($finiteTypes as $constantInteger) {
478: $chars[] = new self($this->value[$constantInteger->getValue()]);
479: }
480: if (!$strLenType->isSuperTypeOf($offsetType)->yes()) {
481: $chars[] = new self('');
482: }
483:
484: return TypeCombinator::union(...$chars);
485: }
486: }
487:
488: return parent::getOffsetValueType($offsetType);
489: }
490:
491: public function setOffsetValueType(?Type $offsetType, Type $valueType, bool $unionValues = true): Type
492: {
493: $valueStringType = $valueType->toString();
494: if ($valueStringType instanceof ErrorType) {
495: return new ErrorType();
496: }
497: if (
498: $offsetType instanceof ConstantIntegerType
499: && $valueStringType instanceof ConstantStringType
500: ) {
501: $value = $this->value;
502: $offsetValue = $offsetType->getValue();
503: if ($offsetValue < 0) {
504: return new ErrorType();
505: }
506: $stringValue = $valueStringType->getValue();
507: if (strlen($stringValue) !== 1) {
508: return new ErrorType();
509: }
510: $value[$offsetValue] = $stringValue;
511:
512: return new self($value);
513: }
514:
515: return parent::setOffsetValueType($offsetType, $valueType);
516: }
517:
518: public function setExistingOffsetValueType(Type $offsetType, Type $valueType): Type
519: {
520: return parent::setOffsetValueType($offsetType, $valueType);
521: }
522:
523: public function append(self $otherString): self
524: {
525: return new self($this->getValue() . $otherString->getValue());
526: }
527:
528: public function generalize(GeneralizePrecision $precision): Type
529: {
530: if ($this->isClassString) {
531: if ($precision->isMoreSpecific()) {
532: return new ClassStringType();
533: }
534:
535: return new StringType();
536: }
537:
538: if ($this->getValue() !== '' && $precision->isMoreSpecific()) {
539: $accessories = [
540: new StringType(),
541: new AccessoryLiteralStringType(),
542: ];
543:
544: if (is_numeric($this->getValue())) {
545: $accessories[] = new AccessoryNumericStringType();
546: }
547:
548: if ($this->getValue() !== '0') {
549: $accessories[] = new AccessoryNonFalsyStringType();
550: } else {
551: $accessories[] = new AccessoryNonEmptyStringType();
552: }
553:
554: if (strtolower($this->getValue()) === $this->getValue()) {
555: $accessories[] = new AccessoryLowercaseStringType();
556: }
557:
558: if (strtoupper($this->getValue()) === $this->getValue()) {
559: $accessories[] = new AccessoryUppercaseStringType();
560: }
561:
562: return new IntersectionType($accessories);
563: }
564:
565: if ($precision->isMoreSpecific()) {
566: return new IntersectionType([
567: new StringType(),
568: new AccessoryLiteralStringType(),
569: ]);
570: }
571:
572: return new StringType();
573: }
574:
575: public function getSmallerType(PhpVersion $phpVersion): Type
576: {
577: $subtractedTypes = [
578: new ConstantBooleanType(true),
579: IntegerRangeType::createAllGreaterThanOrEqualTo((float) $this->value),
580: ];
581:
582: if ($this->value === '') {
583: $subtractedTypes[] = new NullType();
584: $subtractedTypes[] = new StringType();
585: }
586:
587: if (!(bool) $this->value) {
588: $subtractedTypes[] = new ConstantBooleanType(false);
589: }
590:
591: return TypeCombinator::remove(new MixedType(), TypeCombinator::union(...$subtractedTypes));
592: }
593:
594: public function getSmallerOrEqualType(PhpVersion $phpVersion): Type
595: {
596: $subtractedTypes = [
597: IntegerRangeType::createAllGreaterThan((float) $this->value),
598: ];
599:
600: if (!(bool) $this->value) {
601: $subtractedTypes[] = new ConstantBooleanType(true);
602: }
603:
604: return TypeCombinator::remove(new MixedType(), TypeCombinator::union(...$subtractedTypes));
605: }
606:
607: public function getGreaterType(PhpVersion $phpVersion): Type
608: {
609: $subtractedTypes = [
610: new ConstantBooleanType(false),
611: IntegerRangeType::createAllSmallerThanOrEqualTo((float) $this->value),
612: ];
613:
614: if ((bool) $this->value) {
615: $subtractedTypes[] = new ConstantBooleanType(true);
616: }
617:
618: return TypeCombinator::remove(new MixedType(), TypeCombinator::union(...$subtractedTypes));
619: }
620:
621: public function getGreaterOrEqualType(PhpVersion $phpVersion): Type
622: {
623: $subtractedTypes = [
624: IntegerRangeType::createAllSmallerThan((float) $this->value),
625: ];
626:
627: if ((bool) $this->value) {
628: $subtractedTypes[] = new ConstantBooleanType(false);
629: }
630:
631: return TypeCombinator::remove(new MixedType(), TypeCombinator::union(...$subtractedTypes));
632: }
633:
634: public function canAccessConstants(): TrinaryLogic
635: {
636: return $this->isClassString();
637: }
638:
639: public function hasConstant(string $constantName): TrinaryLogic
640: {
641: return $this->getObjectType()->hasConstant($constantName);
642: }
643:
644: public function getConstant(string $constantName): ClassConstantReflection
645: {
646: return $this->getObjectType()->getConstant($constantName);
647: }
648:
649: private function getObjectType(): ObjectType
650: {
651: return $this->objectType ??= new ObjectType($this->value);
652: }
653:
654: public function toPhpDocNode(): TypeNode
655: {
656: if (substr_count($this->value, "\n") > 0) {
657: return $this->generalize(GeneralizePrecision::moreSpecific())->toPhpDocNode();
658: }
659:
660: return new ConstTypeNode(new ConstExprStringNode($this->value, ConstExprStringNode::SINGLE_QUOTED));
661: }
662:
663: public function toValueSet(): ValueSet
664: {
665: return ValueSet::createConstantString($this);
666: }
667:
668: }
669: