Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implemented ConstantStringType inference for str_repeat #1030

Merged
merged 3 commits into from Feb 22, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/Type/Php/StrRepeatFunctionReturnTypeExtension.php
Expand Up @@ -42,6 +42,10 @@ public function getTypeFromFunctionCall(
return new ConstantStringType('');
}

if ($inputType instanceof ConstantStringType && $multiplierType instanceof ConstantIntegerType) {
return new ConstantStringType(str_repeat($inputType->getValue(), $multiplierType->getValue()));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code will crash when analysing code like this: https://3v4l.org/XRaOj

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good point. added a test and made it return NeverType on negative multiplier

}

$accessoryTypes = [];
if ($inputType->isNonEmptyString()->yes()) {
if (IntegerRangeType::fromInterval(1, null)->isSuperTypeOf($multiplierType)->yes()) {
Expand Down
5 changes: 3 additions & 2 deletions tests/PHPStan/Analyser/data/literal-string.php
Expand Up @@ -25,8 +25,9 @@ public function doFoo($literalString, string $string)

assertType('string', str_repeat($string, 10));
assertType('literal-string', str_repeat($literalString, 10));
assertType('literal-string', str_repeat('', 10));
assertType('literal-string&non-empty-string', str_repeat('foo', 10));
assertType("''", str_repeat('', 10));
assertType("'foofoofoofoofoofoofoofoofoofoo'", str_repeat('foo', 10));
assertType("'?,?,?,'", str_repeat('?,', 3));

assertType('non-empty-string', str_pad($string, 5, $string));
assertType('non-empty-string', str_pad($literalString, 5, $string));
Expand Down