Skip to content

Commit a917100

Browse files
authored
infer non-falsy-string in string replace functions
1 parent 14da6b3 commit a917100

File tree

3 files changed

+15
-3
lines changed

3 files changed

+15
-3
lines changed

src/Type/Php/ReplaceFunctionsDynamicReturnTypeExtension.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use PHPStan\Reflection\FunctionReflection;
88
use PHPStan\Reflection\ParametersAcceptorSelector;
99
use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
10+
use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
1011
use PHPStan\Type\ArrayType;
1112
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
1213
use PHPStan\Type\IntersectionType;
@@ -84,6 +85,9 @@ private function getPreliminarilyResolvedTypeFromFunctionCall(
8485
if (count($functionCall->getArgs()) > $replaceArgumentPosition) {
8586
$replaceArgumentType = $scope->getType($functionCall->getArgs()[$replaceArgumentPosition]->value);
8687

88+
if ($subjectArgumentType->isNonFalsyString()->yes() && $replaceArgumentType->isNonFalsyString()->yes()) {
89+
return new IntersectionType([new StringType(), new AccessoryNonFalsyStringType()]);
90+
}
8791
if ($replaceArgumentType->isNonEmptyString()->yes()) {
8892
return new IntersectionType([new StringType(), new AccessoryNonEmptyStringType()]);
8993
}

tests/PHPStan/Analyser/LegacyNodeScopeResolverTest.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7344,15 +7344,15 @@ public function dataReplaceFunctions(): array
73447344
{
73457345
return [
73467346
[
7347-
'non-empty-string',
7347+
'non-falsy-string',
73487348
'$expectedString',
73497349
],
73507350
[
73517351
'string|null',
73527352
'$expectedString2',
73537353
],
73547354
[
7355-
'non-empty-string|null',
7355+
'non-falsy-string|null',
73567356
'$anotherExpectedString',
73577357
],
73587358
[

tests/PHPStan/Analyser/data/non-empty-string-replace-functions.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,12 @@ public function replace(string $search, string $replacement, string $subject){
2323
assertType('non-empty-string', substr_replace($subject, $replacement, 1));
2424
assertType('non-empty-string', substr_replace($subject, $replacement, -1));
2525
}
26-
}
26+
27+
function foo(float $f) {
28+
$s = (string) $f;
29+
assertType('numeric-string', $s);
30+
31+
$price = str_replace(',', '.', $s);
32+
assertType('non-empty-string', $price);
33+
}
34+
}

0 commit comments

Comments
 (0)