Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions src/Type/Php/StrRepeatFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use PHPStan\Type\NeverType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function count;
use function str_repeat;
use function strlen;
Expand Down Expand Up @@ -56,14 +57,23 @@ public function getTypeFromFunctionCall(
}

$inputType = $scope->getType($args[0]->value);
if ($multiplierType instanceof ConstantIntegerType) {
$constantInputStrings = $inputType->getConstantStrings();
if (
count($constantInputStrings) === 1
// don't generate type too big to avoid hitting memory limit
&& strlen($constantInputStrings[0]->getValue()) * $multiplierType->getValue() < 100
) {
return new ConstantStringType(str_repeat($constantInputStrings[0]->getValue(), $multiplierType->getValue()));
$constantInputStrings = $inputType->getConstantStrings();
if (
$multiplierType instanceof ConstantIntegerType
&& count($constantInputStrings) > 0
) {
$length = 0;
foreach ($constantInputStrings as $constantInputString) {
$length += strlen($constantInputString->getValue()) * $multiplierType->getValue();
}

// don't generate type too big to avoid hitting memory limit
if ($length < 100) {
$strings = [];
foreach ($constantInputStrings as $constantInputString) {
$strings[] = new ConstantStringType(str_repeat($constantInputString->getValue(), $multiplierType->getValue()));
}
return TypeCombinator::union(...$strings);
}
}

Expand Down
8 changes: 8 additions & 0 deletions tests/PHPStan/Analyser/nsrt/literal-string.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ public function doFoo($literalString, string $string, $numericString)
"'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'",
str_repeat('a', 99)
);
assertType(
"'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'|'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'",
str_repeat(rand(0,1)?'a':'b', 49)
);
assertType(
"literal-string&lowercase-string&non-falsy-string",
str_repeat(rand(0,1)?'a':'b', 50) // test upper limit
);
assertType('literal-string&lowercase-string&non-falsy-string', str_repeat('a', 100));
assertType('literal-string&non-falsy-string&uppercase-string', str_repeat('A', 100));
assertType('literal-string&lowercase-string&non-empty-string&numeric-string&uppercase-string', str_repeat('0', 100)); // could be non-falsy-string
Expand Down
Loading