Skip to content

Commit c7d91d5

Browse files
phpstan-botstaabm
authored andcommitted
Report str_replace()/str_ireplace()/preg_replace()/preg_filter() calls with fewer replacements than search values
- New bleeding-edge rule `ReplaceCountMismatchRule` (level 5, feature toggle `replaceCountMismatch`): when both the search/pattern and the replace/replacement arguments are arrays and the replacement array size is definitely smaller than the search array size, report it, because PHP silently replaces the remaining values with an empty string. - Uses `Type::getArraySize()` + `isSmallerThan()` so constant arrays, unions of shapes and non-empty lists are handled; only definite mismatches are reported. - A string replacement and an explicitly empty replacement array (a deliberate "remove all" idiom) are not reported. - Applied to the whole family of replace functions with the same semantics: str_replace, str_ireplace, preg_replace, preg_filter. - Respects treatPhpDocTypesAsCertain and adds the tip when only PHPDoc types prove the mismatch.
1 parent de42b4f commit c7d91d5

7 files changed

Lines changed: 276 additions & 0 deletions

File tree

‎conf/bleedingEdge.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,4 @@ parameters:
3535
unusedParameters: true
3636
reuseCollectedDataRuleErrors: true
3737
checkWholePhpVersionRange: true
38+
replaceCountMismatch: true

‎conf/config.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ parameters:
6767
unusedParameters: false
6868
reuseCollectedDataRuleErrors: false
6969
checkWholePhpVersionRange: false
70+
replaceCountMismatch: false
7071
fileExtensions:
7172
- php
7273
checkAdvancedIsset: false

‎conf/parametersSchema.neon‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ parametersSchema:
6464
unusedParameters: bool()
6565
reuseCollectedDataRuleErrors: bool()
6666
checkWholePhpVersionRange: bool()
67+
replaceCountMismatch: bool()
6768
])
6869
fileExtensions: listOf(string())
6970
checkAdvancedIsset: bool()
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules\Functions;
4+
5+
use PhpParser\Node;
6+
use PhpParser\Node\Expr\FuncCall;
7+
use PHPStan\Analyser\ArgumentsNormalizer;
8+
use PHPStan\Analyser\Scope;
9+
use PHPStan\DependencyInjection\AutowiredParameter;
10+
use PHPStan\DependencyInjection\Conditional;
11+
use PHPStan\DependencyInjection\RegisteredRule;
12+
use PHPStan\Php\PhpVersion;
13+
use PHPStan\Reflection\ParametersAcceptorSelector;
14+
use PHPStan\Reflection\ReflectionProvider;
15+
use PHPStan\Rules\Rule;
16+
use PHPStan\Rules\RuleErrorBuilder;
17+
use PHPStan\Type\Type;
18+
use PHPStan\Type\VerbosityLevel;
19+
use function array_key_exists;
20+
use function count;
21+
use function sprintf;
22+
23+
/**
24+
* Reports replace functions called with an array of replacements that is shorter
25+
* than the array of search values. PHP silently replaces the remaining search values
26+
* with an empty string, which is usually a mistake.
27+
*
28+
* @implements Rule<Node\Expr\FuncCall>
29+
*/
30+
#[Conditional(
31+
attribute: new RegisteredRule(level: 5),
32+
if: '%featureToggles.replaceCountMismatch%',
33+
)]
34+
final class ReplaceCountMismatchRule implements Rule
35+
{
36+
37+
private const FUNCTIONS = [
38+
'str_replace' => 'strReplace',
39+
'str_ireplace' => 'strReplace',
40+
'preg_replace' => 'pregReplace',
41+
'preg_filter' => 'pregReplace',
42+
];
43+
44+
public function __construct(
45+
private ReflectionProvider $reflectionProvider,
46+
private PhpVersion $phpVersion,
47+
#[AutowiredParameter]
48+
private bool $treatPhpDocTypesAsCertain,
49+
#[AutowiredParameter(ref: '%tips.treatPhpDocTypesAsCertain%')]
50+
private bool $treatPhpDocTypesAsCertainTip,
51+
)
52+
{
53+
}
54+
55+
public function getNodeType(): string
56+
{
57+
return FuncCall::class;
58+
}
59+
60+
public function processNode(Node $node, Scope $scope): array
61+
{
62+
if (!($node->name instanceof Node\Name)) {
63+
return [];
64+
}
65+
66+
if (!$this->reflectionProvider->hasFunction($node->name, $scope)) {
67+
return [];
68+
}
69+
70+
$functionReflection = $this->reflectionProvider->getFunction($node->name, $scope);
71+
$functionName = $functionReflection->getName();
72+
if (!array_key_exists($functionName, self::FUNCTIONS)) {
73+
return [];
74+
}
75+
76+
$parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
77+
$scope,
78+
$node->getArgs(),
79+
$functionReflection->getVariants(),
80+
$functionReflection->getNamedArgumentsVariants(),
81+
);
82+
83+
$normalizedFuncCall = ArgumentsNormalizer::reorderFuncArguments($parametersAcceptor, $node);
84+
if ($normalizedFuncCall === null) {
85+
return [];
86+
}
87+
88+
$args = $normalizedFuncCall->getArgs();
89+
if (!array_key_exists(0, $args) || !array_key_exists(1, $args)) {
90+
return [];
91+
}
92+
93+
$parameters = $parametersAcceptor->getParameters();
94+
if (count($parameters) < 2) {
95+
return [];
96+
}
97+
98+
if ($this->treatPhpDocTypesAsCertain) {
99+
$searchType = $scope->getType($args[0]->value);
100+
$replaceType = $scope->getType($args[1]->value);
101+
} else {
102+
$searchType = $scope->getNativeType($args[0]->value);
103+
$replaceType = $scope->getNativeType($args[1]->value);
104+
}
105+
106+
if (!$this->hasFewerReplacements($searchType, $replaceType)) {
107+
return [];
108+
}
109+
110+
$errorBuilder = RuleErrorBuilder::message(sprintf(
111+
'Parameter #2 $%s of function %s has fewer elements (%s) than parameter #1 $%s (%s), the remaining values will be replaced with an empty string.',
112+
$parameters[1]->getName(),
113+
$functionName,
114+
$replaceType->getArraySize()->describe(VerbosityLevel::value()),
115+
$parameters[0]->getName(),
116+
$searchType->getArraySize()->describe(VerbosityLevel::value()),
117+
))->identifier(sprintf('%s.replaceCount', self::FUNCTIONS[$functionName]));
118+
119+
if ($this->treatPhpDocTypesAsCertain && $this->treatPhpDocTypesAsCertainTip) {
120+
$nativeSearchType = $scope->getNativeType($args[0]->value);
121+
$nativeReplaceType = $scope->getNativeType($args[1]->value);
122+
if (!$this->hasFewerReplacements($nativeSearchType, $nativeReplaceType)) {
123+
$errorBuilder->treatPhpDocTypesAsCertainTip();
124+
}
125+
}
126+
127+
return [
128+
$errorBuilder->build(),
129+
];
130+
}
131+
132+
private function hasFewerReplacements(Type $searchType, Type $replaceType): bool
133+
{
134+
if (!$searchType->isArray()->yes() || !$replaceType->isArray()->yes()) {
135+
return false;
136+
}
137+
138+
// an explicitly empty array of replacements is a deliberate way to remove all search values
139+
if ($replaceType->isIterableAtLeastOnce()->no()) {
140+
return false;
141+
}
142+
143+
return $replaceType->getArraySize()->isSmallerThan($searchType->getArraySize(), $this->phpVersion)->yes();
144+
}
145+
146+
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Rules\Functions;
4+
5+
use PHPStan\Php\PhpVersion;
6+
use PHPStan\Rules\Rule;
7+
use PHPStan\Testing\RuleTestCase;
8+
use PHPUnit\Framework\Attributes\RequiresPhp;
9+
use const PHP_VERSION_ID;
10+
11+
/**
12+
* @extends RuleTestCase<ReplaceCountMismatchRule>
13+
*/
14+
class ReplaceCountMismatchRuleTest extends RuleTestCase
15+
{
16+
17+
protected function getRule(): Rule
18+
{
19+
return new ReplaceCountMismatchRule(
20+
self::createReflectionProvider(),
21+
new PhpVersion(PHP_VERSION_ID),
22+
true,
23+
true,
24+
);
25+
}
26+
27+
public function testBug3889(): void
28+
{
29+
$this->analyse([__DIR__ . '/data/bug-3889.php'], [
30+
[
31+
'Parameter #2 $replace of function str_replace has fewer elements (2) than parameter #1 $search (3), the remaining values will be replaced with an empty string.',
32+
12,
33+
],
34+
[
35+
'Parameter #2 $replace of function str_ireplace has fewer elements (1) than parameter #1 $search (3), the remaining values will be replaced with an empty string.',
36+
36,
37+
],
38+
[
39+
'Parameter #2 $replace of function str_replace has fewer elements (1) than parameter #1 $search (2), the remaining values will be replaced with an empty string.',
40+
40,
41+
'Because the type is coming from a PHPDoc, you can turn off this check by setting <fg=cyan>treatPhpDocTypesAsCertain: false</> in your <fg=cyan>%configurationFile%</>.',
42+
],
43+
[
44+
'Parameter #2 $replacement of function preg_replace has fewer elements (1) than parameter #1 $pattern (2), the remaining values will be replaced with an empty string.',
45+
46,
46+
],
47+
[
48+
'Parameter #2 $replacement of function preg_filter has fewer elements (1) than parameter #1 $pattern (2), the remaining values will be replaced with an empty string.',
49+
49,
50+
],
51+
]);
52+
}
53+
54+
#[RequiresPhp('>= 8.0')]
55+
public function testNamedArgs(): void
56+
{
57+
$this->analyse([__DIR__ . '/data/bug-3889-named-args.php'], [
58+
[
59+
'Parameter #2 $replace of function str_replace has fewer elements (1) than parameter #1 $search (2), the remaining values will be replaced with an empty string.',
60+
9,
61+
],
62+
]);
63+
}
64+
65+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php // lint >= 8.0
2+
3+
declare(strict_types = 1);
4+
5+
namespace Bug3889NamedArgs;
6+
7+
function doFoo(string $s): void
8+
{
9+
str_replace(search: ['a', 'b'], subject: $s, replace: ['x']);
10+
str_replace(search: ['a', 'b'], subject: $s, replace: ['x', 'y']);
11+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace Bug3889;
4+
5+
class HelloWorld
6+
{
7+
public function sayHello(): void
8+
{
9+
$str = 'Hello';
10+
$search = ['a', 'b', 'c'];
11+
$replace = ['x', 'y'];
12+
echo str_replace($search, $replace, $str);
13+
}
14+
15+
public function replaceIsString(): void
16+
{
17+
$str = 'Hello';
18+
$search = ['a', 'b', 'c'];
19+
echo str_replace($search, 'foo', $str);
20+
}
21+
}
22+
23+
class Variants
24+
{
25+
/**
26+
* @param list<string> $list
27+
* @param non-empty-list<string> $nonEmptyList
28+
* @param array{string, string} $two
29+
* @param array{string, string, string}|array{string} $oneOrThree
30+
*/
31+
public function doFoo(string $s, array $list, array $nonEmptyList, array $two, array $oneOrThree): void
32+
{
33+
str_replace(['a', 'b'], ['x', 'y'], $s);
34+
str_replace(['a', 'b'], ['x', 'y', 'z'], $s);
35+
str_replace(['a', 'b'], [], $s);
36+
str_ireplace(['a', 'b', 'c'], ['x'], $s);
37+
str_replace('a', 'x', $s);
38+
str_replace($list, ['x'], $s);
39+
str_replace($nonEmptyList, ['x'], $s);
40+
str_replace($two, ['x'], $s);
41+
str_replace($two, $nonEmptyList, $s);
42+
str_replace($oneOrThree, ['x'], $s);
43+
str_replace($oneOrThree, [], $s);
44+
str_replace(['a', 'b', 'c'], $oneOrThree, $s);
45+
46+
preg_replace(['/a/', '/b/'], ['x'], $s);
47+
preg_replace(['/a/', '/b/'], ['x', 'y'], $s);
48+
preg_replace(['/a/', '/b/'], 'x', $s);
49+
preg_filter(['/a/', '/b/'], ['x'], $s);
50+
}
51+
}

0 commit comments

Comments
 (0)