Skip to content

Commit f5b3cdf

Browse files
authored
implemented ConstantStringType inference for str_repeat
1 parent 53563e9 commit f5b3cdf

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

src/Type/Php/StrRepeatFunctionReturnTypeExtension.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@
1212
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
1313
use PHPStan\Type\IntegerRangeType;
1414
use PHPStan\Type\IntersectionType;
15+
use PHPStan\Type\NeverType;
1516
use PHPStan\Type\StringType;
1617
use PHPStan\Type\Type;
1718
use function count;
19+
use function str_repeat;
1820

1921
class StrRepeatFunctionReturnTypeExtension implements DynamicFunctionReturnTypeExtension
2022
{
@@ -42,6 +44,14 @@ public function getTypeFromFunctionCall(
4244
return new ConstantStringType('');
4345
}
4446

47+
if ($multiplierType instanceof ConstantIntegerType && $multiplierType->getValue() < 0) {
48+
return new NeverType();
49+
}
50+
51+
if ($inputType instanceof ConstantStringType && $multiplierType instanceof ConstantIntegerType) {
52+
return new ConstantStringType(str_repeat($inputType->getValue(), $multiplierType->getValue()));
53+
}
54+
4555
$accessoryTypes = [];
4656
if ($inputType->isNonEmptyString()->yes()) {
4757
if (IntegerRangeType::fromInterval(1, null)->isSuperTypeOf($multiplierType)->yes()) {

tests/PHPStan/Analyser/data/literal-string.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,10 @@ public function doFoo($literalString, string $string)
2525

2626
assertType('string', str_repeat($string, 10));
2727
assertType('literal-string', str_repeat($literalString, 10));
28-
assertType('literal-string', str_repeat('', 10));
29-
assertType('literal-string&non-empty-string', str_repeat('foo', 10));
28+
assertType("''", str_repeat('', 10));
29+
assertType("'foofoofoofoofoofoofoofoofoofoo'", str_repeat('foo', 10));
30+
assertType("'?,?,?,'", str_repeat('?,', 3));
31+
assertType("*NEVER*", str_repeat('?,', -3));
3032

3133
assertType('non-empty-string', str_pad($string, 5, $string));
3234
assertType('non-empty-string', str_pad($literalString, 5, $string));

0 commit comments

Comments
 (0)