Skip to content

Fix handling of str_split / mb_str_split string arg compound types + default return type for mb_str_split #1496

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

Merged
merged 2 commits into from
Jul 10, 2022
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
2 changes: 1 addition & 1 deletion build/baseline-8.0.neon
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ parameters:
path: ../src/Type/Php/MbStrlenFunctionReturnTypeExtension.php

-
message: "#^Strict comparison using \\=\\=\\= between non-empty-array<int, string> and false will always evaluate to false\\.$#"
message: "#^Strict comparison using \\=\\=\\= between array<int, string> and false will always evaluate to false\\.$#"
count: 1
path: ../src/Type/Php/StrSplitFunctionReturnTypeExtension.php

Expand Down
2 changes: 1 addition & 1 deletion resources/functionMap_php74delta.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
'FFI::typeof' => ['FFI\CType', '&ptr'=>'FFI\CData'],
'FFI::type' => ['FFI\CType', 'type'=>'string'],
'get_mangled_object_vars' => ['array', 'obj'=>'object'],
'mb_str_split' => ['non-empty-array<int,string>|false', 'str'=>'string', 'split_length='=>'int', 'encoding='=>'string'],
'mb_str_split' => ['array<int,string>|false', 'str'=>'string', 'split_length='=>'int', 'encoding='=>'string'],
'password_algos' => ['array<int, string>'],
'password_hash' => ['string|false', 'password'=>'string', 'algo'=>'string|null', 'options='=>'array'],
'password_needs_rehash' => ['bool', 'hash'=>'string', 'algo'=>'string|null', 'options='=>'array'],
Expand Down
2 changes: 1 addition & 1 deletion resources/functionMap_php80delta.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
'imagescale' => ['false|object', 'im'=>'resource', 'new_width'=>'int', 'new_height='=>'int', 'method='=>'int'],
'ldap_set_rebind_proc' => ['bool', 'ldap'=>'resource', 'callback'=>'?callable'],
'mb_decode_numericentity' => ['string|false', 'string'=>'string', 'convmap'=>'array', 'encoding='=>'string'],
'mb_str_split' => ['non-empty-array<int,string>', 'str'=>'string', 'split_length='=>'positive-int', 'encoding='=>'string'],
'mb_str_split' => ['array<int,string>', 'str'=>'string', 'split_length='=>'positive-int', 'encoding='=>'string'],
'mb_strlen' => ['0|positive-int', 'str'=>'string', 'encoding='=>'string'],
'mktime' => ['int|false', 'hour'=>'int', 'minute='=>'int', 'second='=>'int', 'month='=>'int', 'day='=>'int', 'year='=>'int'],
'odbc_exec' => ['resource|false', 'connection_id'=>'resource', 'query'=>'string'],
Expand Down
41 changes: 27 additions & 14 deletions src/Type/Php/StrSplitFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,13 @@
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\IntegerType;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeTraverser;
use PHPStan\Type\TypeUtils;
use PHPStan\Type\UnionType;
use function array_map;
use function array_unique;
use function count;
Expand Down Expand Up @@ -62,6 +65,7 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
$splitLength = 1;
}

$encoding = null;
if ($functionReflection->getName() === 'mb_str_split') {
if (count($functionCall->getArgs()) >= 3) {
$strings = TypeUtils::getConstantStrings($scope->getType($functionCall->getArgs()[2]->value));
Expand All @@ -85,22 +89,31 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
}

$stringType = $scope->getType($functionCall->getArgs()[0]->value);
if (!$stringType instanceof ConstantStringType) {
return TypeCombinator::intersect(
new ArrayType(new IntegerType(), new StringType()),
new NonEmptyArrayType(),
);
}
$stringValue = $stringType->getValue();

$items = isset($encoding)
? mb_str_split($stringValue, $splitLength, $encoding)
: str_split($stringValue, $splitLength);
if ($items === false) {
throw new ShouldNotHappenException();
}
return TypeTraverser::map($stringType, static function (Type $type, callable $traverse) use ($encoding, $splitLength, $scope): Type {
if ($type instanceof UnionType || $type instanceof IntersectionType) {
return $traverse($type);
}

if (!$type instanceof ConstantStringType) {
$returnType = new ArrayType(new IntegerType(), new StringType());

return $encoding === null
? TypeCombinator::intersect($returnType, new NonEmptyArrayType())
: $returnType;
}

$stringValue = $type->getValue();

$items = $encoding === null
? str_split($stringValue, $splitLength)
: mb_str_split($stringValue, $splitLength, $encoding);
if ($items === false) {
throw new ShouldNotHappenException();
}

return self::createConstantArrayFrom($items, $scope);
return self::createConstantArrayFrom($items, $scope);
});
}

/**
Expand Down
28 changes: 14 additions & 14 deletions tests/PHPStan/Analyser/LegacyNodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5356,7 +5356,7 @@ public function dataFunctions(): array
'$strSplitConstantStringWithInvalidSplitLengthType',
],
[
'non-empty-array<int, string>',
'array{\'a\'|\'g\', \'b\'|\'h\', \'c\'|\'i\', \'d\'|\'j\', \'e\'|\'k\', \'f\'|\'l\'}',
'$strSplitConstantStringWithVariableStringAndConstantSplitLength',
],
[
Expand Down Expand Up @@ -8716,15 +8716,15 @@ public function dataPhp74Functions(): array
{
return [
[
PHP_VERSION_ID < 80000 ? 'non-empty-array<int, string>|false' : 'non-empty-array<int, string>',
PHP_VERSION_ID < 80000 ? 'array<int, string>|false' : 'array<int, string>',
'$mbStrSplitConstantStringWithoutDefinedParameters',
],
[
'array{\'a\', \'b\', \'c\', \'d\', \'e\', \'f\'}',
'$mbStrSplitConstantStringWithoutDefinedSplitLength',
],
[
'non-empty-array<int, string>',
'array<int, string>',
'$mbStrSplitStringWithoutDefinedSplitLength',
],
[
Expand All @@ -8740,15 +8740,15 @@ public function dataPhp74Functions(): array
'$mbStrSplitConstantStringWithFailureSplitLength',
],
[
PHP_VERSION_ID < 80000 ? 'non-empty-array<int, string>|false' : 'non-empty-array<int, string>',
PHP_VERSION_ID < 80000 ? 'array<int, string>|false' : 'array<int, string>',
'$mbStrSplitConstantStringWithInvalidSplitLengthType',
],
[
'non-empty-array<int, string>',
'array{\'a\'|\'g\', \'b\'|\'h\', \'c\'|\'i\', \'d\'|\'j\', \'e\'|\'k\', \'f\'|\'l\'}',
'$mbStrSplitConstantStringWithVariableStringAndConstantSplitLength',
],
[
PHP_VERSION_ID < 80000 ? 'non-empty-array<int, string>|false' : 'non-empty-array<int, string>',
PHP_VERSION_ID < 80000 ? 'array<int, string>|false' : 'array<int, string>',
'$mbStrSplitConstantStringWithVariableStringAndVariableSplitLength',
],
[
Expand All @@ -8760,7 +8760,7 @@ public function dataPhp74Functions(): array
'$mbStrSplitConstantStringWithOneSplitLengthAndInvalidEncoding',
],
[
PHP_VERSION_ID < 80000 ? 'non-empty-array<int, string>|false' : 'non-empty-array<int, string>',
PHP_VERSION_ID < 80000 ? 'array<int, string>|false' : 'array<int, string>',
'$mbStrSplitConstantStringWithOneSplitLengthAndVariableEncoding',
],
[
Expand All @@ -8772,7 +8772,7 @@ public function dataPhp74Functions(): array
'$mbStrSplitConstantStringWithGreaterSplitLengthThanStringLengthAndInvalidEncoding',
],
[
PHP_VERSION_ID < 80000 ? 'non-empty-array<int, string>|false' : 'non-empty-array<int, string>',
PHP_VERSION_ID < 80000 ? 'array<int, string>|false' : 'array<int, string>',
'$mbStrSplitConstantStringWithGreaterSplitLengthThanStringLengthAndVariableEncoding',
],
[
Expand All @@ -8788,39 +8788,39 @@ public function dataPhp74Functions(): array
'$mbStrSplitConstantStringWithFailureSplitLengthAndVariableEncoding',
],
[
PHP_VERSION_ID < 80000 ? 'non-empty-array<int, string>|false' : 'non-empty-array<int, string>',
PHP_VERSION_ID < 80000 ? 'array<int, string>|false' : 'array<int, string>',
'$mbStrSplitConstantStringWithInvalidSplitLengthTypeAndValidEncoding',
],
[
'false',
'$mbStrSplitConstantStringWithInvalidSplitLengthTypeAndInvalidEncoding',
],
[
PHP_VERSION_ID < 80000 ? 'non-empty-array<int, string>|false' : 'non-empty-array<int, string>',
PHP_VERSION_ID < 80000 ? 'array<int, string>|false' : 'array<int, string>',
'$mbStrSplitConstantStringWithInvalidSplitLengthTypeAndVariableEncoding',
],
[
'non-empty-array<int, string>',
'array{\'a\'|\'g\', \'b\'|\'h\', \'c\'|\'i\', \'d\'|\'j\', \'e\'|\'k\', \'f\'|\'l\'}',
'$mbStrSplitConstantStringWithVariableStringAndConstantSplitLengthAndValidEncoding',
],
[
'false',
'$mbStrSplitConstantStringWithVariableStringAndConstantSplitLengthAndInvalidEncoding',
],
[
PHP_VERSION_ID < 80000 ? 'non-empty-array<int, string>|false' : 'non-empty-array<int, string>',
PHP_VERSION_ID < 80000 ? 'array<int, string>|false' : 'array<int, string>',
'$mbStrSplitConstantStringWithVariableStringAndConstantSplitLengthAndVariableEncoding',
],
[
PHP_VERSION_ID < 80000 ? 'non-empty-array<int, string>|false' : 'non-empty-array<int, string>',
PHP_VERSION_ID < 80000 ? 'array<int, string>|false' : 'array<int, string>',
'$mbStrSplitConstantStringWithVariableStringAndVariableSplitLengthAndValidEncoding',
],
[
'false',
'$mbStrSplitConstantStringWithVariableStringAndVariableSplitLengthAndInvalidEncoding',
],
[
PHP_VERSION_ID < 80000 ? 'non-empty-array<int, string>|false' : 'non-empty-array<int, string>',
PHP_VERSION_ID < 80000 ? 'array<int, string>|false' : 'array<int, string>',
'$mbStrSplitConstantStringWithVariableStringAndVariableSplitLengthAndVariableEncoding',
],
];
Expand Down
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -923,6 +923,7 @@ public function dataFileAsserts(): iterable
yield from $this->gatherAssertTypes(__DIR__ . '/data/emptyiterator.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/collected-data.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-7550.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-7580.php');
}

/**
Expand Down
18 changes: 18 additions & 0 deletions tests/PHPStan/Analyser/data/bug-7580.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php declare(strict_types = 1);

namespace Bug7580;

use function PHPStan\Testing\assertType;

assertType('array{}', mb_str_split('', 1));

assertType('array{\'x\'}', mb_str_split('x', 1));

$v = (string) (mt_rand() === 0 ? '' : 'x');
assertType('\'\'|\'x\'', $v);
assertType('array{}|array{\'x\'}', mb_str_split($v, 1));

function x(): string { throw new \Exception(); };
$v = x();
assertType('string', $v);
assertType('array<int, string>', mb_str_split($v, 1));
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,19 @@ public function testReportPhpDoc(): void
]);
}

public function testBug7580(): void
{
$this->treatPhpDocTypesAsCertain = false;
$this->analyse([__DIR__ . '/data/bug-7580.php'], [
[
'Ternary operator condition is always false.',
6,
],
[
'Ternary operator condition is always true.',
9,
],
]);
}

}
20 changes: 20 additions & 0 deletions tests/PHPStan/Rules/Comparison/data/bug-7580.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php declare(strict_types = 1);

namespace Bug7580;

print_r(mb_str_split('', 1));
print_r(mb_str_split('', 1) ?: ['']);

print_r(mb_str_split('x', 1));
print_r(mb_str_split('x', 1) ?: ['']);

$v = (string) (mt_rand() === 0 ? '' : 'x');
\PHPStan\dumpType($v);
print_r(mb_str_split($v, 1));
print_r(mb_str_split($v, 1) ?: ['']); // there must be no phpstan error for this line

function x(): string { throw new \Exception(); };
$v = x();
\PHPStan\dumpType($v);
print_r(mb_str_split($v, 1));
print_r(mb_str_split($v, 1) ?: ['']); // there must be no phpstan error for this line