Skip to content

Commit a29dc57

Browse files
fluffycondorondrejmirtes
authored andcommitted
Add support for int and bool args for strlen
1 parent f584311 commit a29dc57

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

src/Type/Php/StrlenFunctionReturnTypeExtension.php

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
1212
use PHPStan\Type\IntegerRangeType;
1313
use PHPStan\Type\IntegerType;
14+
use PHPStan\Type\StringType;
1415
use PHPStan\Type\Type;
1516
use PHPStan\Type\TypeUtils;
1617
use function count;
@@ -37,11 +38,19 @@ public function getTypeFromFunctionCall(
3738

3839
$argType = $scope->getType($args[0]->value);
3940

40-
$constantStrings = TypeUtils::getConstantStrings($argType);
41+
$constantScalars = TypeUtils::getConstantScalars($argType);
4142
$min = null;
4243
$max = null;
43-
foreach ($constantStrings as $constantString) {
44-
$len = strlen($constantString->getValue());
44+
foreach ($constantScalars as $constantScalar) {
45+
if ((new IntegerType())->isSuperTypeOf($constantScalar)->yes()) {
46+
$len = strlen((string) $constantScalar->getValue());
47+
} elseif ((new StringType())->isSuperTypeOf($constantScalar)->yes()) {
48+
$len = strlen((string) $constantScalar->getValue());
49+
} elseif ((new BooleanType())->isSuperTypeOf($constantScalar)->yes()) {
50+
$len = strlen((string) $constantScalar->getValue());
51+
} else {
52+
break;
53+
}
4554

4655
if ($min === null) {
4756
$min = $len;

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

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,8 +280,9 @@ class MoreNonEmptyStringFunctions
280280
/**
281281
* @param non-empty-string $nonEmpty
282282
* @param '1'|'2'|'5'|'10' $constUnion
283+
* @param 1|2|5|10|123|'1234'|false $constUnionMixed
283284
*/
284-
public function doFoo(string $s, string $nonEmpty, int $i, bool $bool, $constUnion)
285+
public function doFoo(string $s, string $nonEmpty, int $i, bool $bool, $constUnion, $constUnionMixed)
285286
{
286287
assertType('string', addslashes($s));
287288
assertType('non-empty-string', addslashes($nonEmpty));
@@ -336,6 +337,10 @@ public function doFoo(string $s, string $nonEmpty, int $i, bool $bool, $constUni
336337
assertType('int<0, max>', strlen($s));
337338
assertType('int<1, max>', strlen($nonEmpty));
338339
assertType('int<1, 2>', strlen($constUnion));
340+
assertType('int<0, 4>', strlen($constUnionMixed));
341+
assertType('3', strlen(123));
342+
assertType('1', strlen(true));
343+
assertType('0', strlen(false));
339344

340345
assertType('non-empty-string', str_pad($nonEmpty, 0));
341346
assertType('non-empty-string', str_pad($nonEmpty, 1));

0 commit comments

Comments
 (0)