Skip to content

Improve ReplaceFunctionsDynamicReturnTypeExtension #4023

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

Open
wants to merge 5 commits into
base: 2.1.x
Choose a base branch
from
Open
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
130 changes: 81 additions & 49 deletions src/Type/Php/ReplaceFunctionsDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Type\Accessory\AccessoryArrayListType;
use PHPStan\Type\Accessory\AccessoryLowercaseStringType;
use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
use PHPStan\Type\Accessory\AccessoryNonFalsyStringType;
use PHPStan\Type\Accessory\AccessoryUppercaseStringType;
use PHPStan\Type\Accessory\NonEmptyArrayType;
use PHPStan\Type\ArrayType;
use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\IntersectionType;
Expand Down Expand Up @@ -84,6 +87,7 @@ private function getPreliminarilyResolvedTypeFromFunctionCall(
return TypeUtils::toBenevolentUnion($defaultReturnType);
}

$replaceArgumentType = null;
if (array_key_exists($functionReflection->getName(), self::FUNCTIONS_REPLACE_POSITION)) {
$replaceArgumentPosition = self::FUNCTIONS_REPLACE_POSITION[$functionReflection->getName()];

Expand All @@ -92,68 +96,96 @@ private function getPreliminarilyResolvedTypeFromFunctionCall(
if ($replaceArgumentType->isArray()->yes()) {
$replaceArgumentType = $replaceArgumentType->getIterableValueType();
}
}
}

$accessories = [];
if ($subjectArgumentType->isNonFalsyString()->yes() && $replaceArgumentType->isNonFalsyString()->yes()) {
$accessories[] = new AccessoryNonFalsyStringType();
} elseif ($subjectArgumentType->isNonEmptyString()->yes() && $replaceArgumentType->isNonEmptyString()->yes()) {
$accessories[] = new AccessoryNonEmptyStringType();
}
$result = [];

if ($subjectArgumentType->isLowercaseString()->yes() && $replaceArgumentType->isLowercaseString()->yes()) {
$accessories[] = new AccessoryLowercaseStringType();
}
if ($subjectArgumentType->isString()->yes()) {
$stringArgumentType = $subjectArgumentType;
} else {
$stringArgumentType = TypeCombinator::intersect(new StringType(), $subjectArgumentType);
}
if ($stringArgumentType->isString()->yes()) {
$result[] = $this->getReplaceType($stringArgumentType, $replaceArgumentType);
}

if ($subjectArgumentType->isUppercaseString()->yes() && $replaceArgumentType->isUppercaseString()->yes()) {
$accessories[] = new AccessoryUppercaseStringType();
if ($subjectArgumentType->isArray()->yes()) {
$arrayArgumentType = $subjectArgumentType;
} else {
$arrayArgumentType = TypeCombinator::intersect(new ArrayType(new MixedType(), new MixedType()), $subjectArgumentType);
}
if ($arrayArgumentType->isArray()->yes()) {
$keyShouldBeOptional = in_array(
$functionReflection->getName(),
['preg_replace', 'preg_replace_callback', 'preg_replace_callback_array'],
true,
);

$constantArrays = $arrayArgumentType->getConstantArrays();
if ($constantArrays !== []) {
foreach ($constantArrays as $constantArray) {
$valueTypes = $constantArray->getValueTypes();

$builder = ConstantArrayTypeBuilder::createEmpty();
foreach ($constantArray->getKeyTypes() as $index => $keyType) {
$builder->setOffsetValueType(
$keyType,
$this->getReplaceType($valueTypes[$index], $replaceArgumentType),
$keyShouldBeOptional || $constantArray->isOptionalKey($index),
);
}
$result[] = $builder->getArray();
}

if (count($accessories) > 0) {
$accessories[] = new StringType();
return new IntersectionType($accessories);
} else {
$newArrayType = new ArrayType(
$arrayArgumentType->getIterableKeyType(),
$this->getReplaceType($arrayArgumentType->getIterableValueType(), $replaceArgumentType),
);
if ($arrayArgumentType->isList()->yes()) {
$newArrayType = TypeCombinator::intersect($newArrayType, new AccessoryArrayListType());
}
if ($arrayArgumentType->isIterableAtLeastOnce()->yes()) {
$newArrayType = TypeCombinator::intersect($newArrayType, new NonEmptyArrayType());
}

$result[] = $newArrayType;
}
}

$isStringSuperType = $subjectArgumentType->isString();
$isArraySuperType = $subjectArgumentType->isArray();
$compareSuperTypes = $isStringSuperType->compareTo($isArraySuperType);
if ($compareSuperTypes === $isStringSuperType) {
return TypeCombinator::union(...$result);
}

private function getReplaceType(
Type $subjectArgumentType,
?Type $replaceArgumentType,
): Type
{
if ($replaceArgumentType === null) {
return new StringType();
} elseif ($compareSuperTypes === $isArraySuperType) {
$subjectArrays = $subjectArgumentType->getArrays();
if (count($subjectArrays) > 0) {
$result = [];
foreach ($subjectArrays as $arrayType) {
$constantArrays = $arrayType->getConstantArrays();

if (
$constantArrays !== []
&& in_array($functionReflection->getName(), ['preg_replace', 'preg_replace_callback', 'preg_replace_callback_array'], true)
) {
foreach ($constantArrays as $constantArray) {
$generalizedArray = $constantArray->generalizeValues();

$builder = ConstantArrayTypeBuilder::createEmpty();
// turn all keys optional
foreach ($constantArray->getKeyTypes() as $keyType) {
$builder->setOffsetValueType($keyType, $generalizedArray->getOffsetValueType($keyType), true);
}
$result[] = $builder->getArray();
}

continue;
}
}

$result[] = $arrayType->generalizeValues();
}
$accessories = [];
if ($subjectArgumentType->isNonFalsyString()->yes() && $replaceArgumentType->isNonFalsyString()->yes()) {
$accessories[] = new AccessoryNonFalsyStringType();
} elseif ($subjectArgumentType->isNonEmptyString()->yes() && $replaceArgumentType->isNonEmptyString()->yes()) {
$accessories[] = new AccessoryNonEmptyStringType();
}

return TypeCombinator::union(...$result);
}
return $subjectArgumentType;
if ($subjectArgumentType->isLowercaseString()->yes() && $replaceArgumentType->isLowercaseString()->yes()) {
$accessories[] = new AccessoryLowercaseStringType();
}

if ($subjectArgumentType->isUppercaseString()->yes() && $replaceArgumentType->isUppercaseString()->yes()) {
$accessories[] = new AccessoryUppercaseStringType();
}

if (count($accessories) > 0) {
$accessories[] = new StringType();
return new IntersectionType($accessories);
}

return $defaultReturnType;
return new StringType();
}

private function getSubjectType(
Expand Down
9 changes: 4 additions & 5 deletions stubs/core.stub
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ function preg_match($pattern, $subject, &$matches = [], int $flags = 0, int $off
* @param string|array<string|int|float> $subject
* @param int $count
* @param-out 0|positive-int $count
* @return ($subject is array ? list<string>|null : string|null)
* @return ($subject is array ? array<string>|null : string|null)
*/
function preg_replace_callback($pattern, $callback, $subject, int $limit = -1, &$count = null, int $flags = 0) {}

Expand All @@ -237,7 +237,7 @@ function preg_replace_callback($pattern, $callback, $subject, int $limit = -1, &
* @param string|array<string|int|float> $subject
* @param int $count
* @param-out 0|positive-int $count
* @return ($subject is array ? list<string>|null : string|null)
* @return ($subject is array ? array<string>|null : string|null)
*/
function preg_replace($pattern, $replacement, $subject, int $limit = -1, &$count = null) {}

Expand All @@ -256,7 +256,7 @@ function preg_filter($pattern, $replacement, $subject, int $limit = -1, &$count
* @param array<string>|string $replace
* @param array<string>|string $subject
* @param-out int $count
* @return list<string>|string
* @return array<string>|string
*/
function str_replace($search, $replace, $subject, ?int &$count = null) {}

Expand All @@ -265,7 +265,7 @@ function str_replace($search, $replace, $subject, ?int &$count = null) {}
* @param array<string>|string $replace
* @param array<string>|string $subject
* @param-out int $count
* @return list<string>|string
* @return array<string>|string
*/
function str_ireplace($search, $replace, $subject, ?int &$count = null) {}

Expand Down Expand Up @@ -326,4 +326,3 @@ function get_defined_constants(bool $categorize = false): array {}
* @return __benevolent<array<string,string>|array<string,false>|array<string,list<mixed>>|false>
*/
function getopt(string $short_options, array $long_options = [], &$rest_index = null) {}

12 changes: 6 additions & 6 deletions tests/PHPStan/Analyser/LegacyNodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7454,31 +7454,31 @@ public function dataReplaceFunctions(): array
'$anotherExpectedString',
],
[
'array{a: string, b: string}',
'array{a: lowercase-string&non-falsy-string, b: lowercase-string&non-falsy-string}',
'$expectedArray',
],
[
'array{a?: string, b?: string}',
'$expectedArray2',
],
[
'array{a?: string, b?: string}',
'array{a?: lowercase-string&non-falsy-string, b?: lowercase-string&non-falsy-string}',
'$anotherExpectedArray',
],
[
'list<string>|string',
'array{}|(lowercase-string&non-falsy-string)',
'$expectedArrayOrString',
],
[
'(list<string>|string)',
'(array<string>|string)',
'$expectedBenevolentArrayOrString',
],
[
'list<string>|string|null',
'array{}|string|null',
'$expectedArrayOrString2',
],
[
'list<string>|string|null',
'array{}|(lowercase-string&non-falsy-string)|null',
'$anotherExpectedArrayOrString',
],
[
Expand Down
2 changes: 1 addition & 1 deletion tests/PHPStan/Analyser/nsrt/bug-11547.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ function validPatternWithEmptyResult(string $s, array $arr) {
assertType('string|null', $r);

$r = preg_replace('/(\D+)*[12]/', 'x', $arr);
assertType('array', $r);
assertType('array<string>', $r);
}


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

namespace Bug9870;

use function PHPStan\Testing\assertType;

class HelloWorld
{
/**
* @param non-empty-string|list<non-empty-string> $date
*/
public function sayHello($date): void
{
if (is_string($date)) {
assertType('non-empty-string', str_replace('-', '/', $date));
} else {
assertType('list<non-empty-string>', str_replace('-', '/', $date));
}
assertType('list<non-empty-string>|non-empty-string', str_replace('-', '/', $date));
}

/**
* @param string|array<string> $stringOrArray
* @param non-empty-string|array<string> $nonEmptyStringOrArray
* @param string|array<non-empty-string> $stringOrArrayNonEmptyString
* @param string|non-empty-array<string> $stringOrNonEmptyArray
* @param string|array<string>|bool|int $wrongParam
*/
public function moreCheck(
$stringOrArray,
$nonEmptyStringOrArray,
$stringOrArrayNonEmptyString,
$stringOrNonEmptyArray,
$wrongParam,
): void {
assertType('array<string>|string', str_replace('-', '/', $stringOrArray));
assertType('array<string>|non-empty-string', str_replace('-', '/', $nonEmptyStringOrArray));
assertType('array<non-empty-string>|string', str_replace('-', '/', $stringOrArrayNonEmptyString));
assertType('non-empty-array<string>|string', str_replace('-', '/', $stringOrNonEmptyArray));
assertType('array<string>|string', str_replace('-', '/', $wrongParam));
assertType('array<string>|string', str_replace('-', '/'));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -103,15 +103,15 @@ public function testRule(): void
122,
],
[
'Binary operation "." between array and \'xyz\' results in an error.',
'Binary operation "." between array<string> and \'xyz\' results in an error.',
127,
],
[
'Binary operation "." between list<string>|string and \'xyz\' results in an error.',
'Binary operation "." between array{}|non-falsy-string and \'xyz\' results in an error.',
134,
],
[
'Binary operation "+" between (list<string>|string) and 1 results in an error.',
'Binary operation "+" between (array<string>|string) and 1 results in an error.',
136,
],
[
Expand Down
Loading