Repository navigation
Report str_replace()/str_ireplace()/preg_replace()/preg_filter() calls with fewer replacements than search values
#7007
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
phpstan-bot
wants to merge
4
commits into
phpstan:2.3.x
Choose a base branch
from
phpstan-bot:create-pull-request/patch-kniiekt
base: 2.3.x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
c7d91d5
Report `str_replace()`/`str_ireplace()`/`preg_replace()`/`preg_filter…
phpstan-bot fbd8666
Bail out early in ReplaceCountMismatchRule when the call has fewer th…
phpstan-bot 75d824b
Use argument.replaceCount identifier in ReplaceCountMismatchRule
phpstan-bot 0bcc270
Simplify ReplaceCountMismatchRule error message
phpstan-bot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| <?php declare(strict_types = 1); | ||
|
|
||
| namespace PHPStan\Rules\Functions; | ||
|
|
||
| use PhpParser\Node; | ||
| use PhpParser\Node\Expr\FuncCall; | ||
| use PHPStan\Analyser\ArgumentsNormalizer; | ||
| use PHPStan\Analyser\Scope; | ||
| use PHPStan\DependencyInjection\AutowiredParameter; | ||
| use PHPStan\DependencyInjection\Conditional; | ||
| use PHPStan\DependencyInjection\RegisteredRule; | ||
| use PHPStan\Php\PhpVersion; | ||
| use PHPStan\Reflection\ParametersAcceptorSelector; | ||
| use PHPStan\Reflection\ReflectionProvider; | ||
| use PHPStan\Rules\Rule; | ||
| use PHPStan\Rules\RuleErrorBuilder; | ||
| use PHPStan\Type\Type; | ||
| use function array_key_exists; | ||
| use function count; | ||
| use function sprintf; | ||
|
|
||
| /** | ||
| * Reports replace functions called with an array of replacements that is shorter | ||
| * than the array of search values. PHP silently replaces the remaining search values | ||
| * with an empty string, which is usually a mistake. | ||
| * | ||
| * @implements Rule<Node\Expr\FuncCall> | ||
| */ | ||
| #[Conditional( | ||
| attribute: new RegisteredRule(level: 5), | ||
| if: '%featureToggles.replaceCountMismatch%', | ||
| )] | ||
| final class ReplaceCountMismatchRule implements Rule | ||
| { | ||
|
|
||
| private const FUNCTIONS = [ | ||
| 'str_replace' => true, | ||
| 'str_ireplace' => true, | ||
| 'preg_replace' => true, | ||
| 'preg_filter' => true, | ||
| ]; | ||
|
|
||
| public function __construct( | ||
| private ReflectionProvider $reflectionProvider, | ||
| private PhpVersion $phpVersion, | ||
| #[AutowiredParameter] | ||
| private bool $treatPhpDocTypesAsCertain, | ||
| #[AutowiredParameter(ref: '%tips.treatPhpDocTypesAsCertain%')] | ||
| private bool $treatPhpDocTypesAsCertainTip, | ||
| ) | ||
| { | ||
| } | ||
|
|
||
| public function getNodeType(): string | ||
| { | ||
| return FuncCall::class; | ||
| } | ||
|
|
||
| public function processNode(Node $node, Scope $scope): array | ||
| { | ||
| if (count($node->getArgs()) < 2) { | ||
| return []; | ||
| } | ||
|
|
||
| if (!($node->name instanceof Node\Name)) { | ||
| return []; | ||
| } | ||
|
|
||
| if (!$this->reflectionProvider->hasFunction($node->name, $scope)) { | ||
| return []; | ||
| } | ||
|
|
||
| $functionReflection = $this->reflectionProvider->getFunction($node->name, $scope); | ||
| $functionName = $functionReflection->getName(); | ||
| if (!array_key_exists($functionName, self::FUNCTIONS)) { | ||
| return []; | ||
| } | ||
|
|
||
| $parametersAcceptor = ParametersAcceptorSelector::selectFromArgs( | ||
| $scope, | ||
| $node->getArgs(), | ||
| $functionReflection->getVariants(), | ||
| $functionReflection->getNamedArgumentsVariants(), | ||
| ); | ||
|
|
||
| $normalizedFuncCall = ArgumentsNormalizer::reorderFuncArguments($parametersAcceptor, $node); | ||
| if ($normalizedFuncCall === null) { | ||
| return []; | ||
| } | ||
|
|
||
| // named arguments can leave a gap in the normalized arguments when a required one is missing | ||
| $args = $normalizedFuncCall->getArgs(); | ||
| if (!array_key_exists(0, $args) || !array_key_exists(1, $args)) { | ||
| return []; | ||
| } | ||
|
|
||
| if ($this->treatPhpDocTypesAsCertain) { | ||
| $searchType = $scope->getType($args[0]->value); | ||
| $replaceType = $scope->getType($args[1]->value); | ||
| } else { | ||
| $searchType = $scope->getNativeType($args[0]->value); | ||
| $replaceType = $scope->getNativeType($args[1]->value); | ||
| } | ||
|
|
||
| if (!$this->hasFewerReplacements($searchType, $replaceType)) { | ||
| return []; | ||
| } | ||
|
|
||
| $errorBuilder = RuleErrorBuilder::message(sprintf( | ||
| 'Call to %s is using fewer replacements than search values.', | ||
| $functionName, | ||
| ))->identifier('argument.replaceCount'); | ||
|
|
||
| if ($this->treatPhpDocTypesAsCertain && $this->treatPhpDocTypesAsCertainTip) { | ||
| $nativeSearchType = $scope->getNativeType($args[0]->value); | ||
| $nativeReplaceType = $scope->getNativeType($args[1]->value); | ||
| if (!$this->hasFewerReplacements($nativeSearchType, $nativeReplaceType)) { | ||
| $errorBuilder->treatPhpDocTypesAsCertainTip(); | ||
| } | ||
| } | ||
|
|
||
| return [ | ||
| $errorBuilder->build(), | ||
| ]; | ||
| } | ||
|
|
||
| private function hasFewerReplacements(Type $searchType, Type $replaceType): bool | ||
| { | ||
| if (!$searchType->isArray()->yes() || !$replaceType->isArray()->yes()) { | ||
| return false; | ||
| } | ||
|
|
||
| // an explicitly empty array of replacements is a deliberate way to remove all search values | ||
| if ($replaceType->isIterableAtLeastOnce()->no()) { | ||
| return false; | ||
| } | ||
|
|
||
| return $replaceType->getArraySize()->isSmallerThan($searchType->getArraySize(), $this->phpVersion)->yes(); | ||
| } | ||
|
|
||
| } | ||
65 changes: 65 additions & 0 deletions
65
tests/PHPStan/Rules/Functions/ReplaceCountMismatchRuleTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| <?php declare(strict_types = 1); | ||
|
|
||
| namespace PHPStan\Rules\Functions; | ||
|
|
||
| use PHPStan\Php\PhpVersion; | ||
| use PHPStan\Rules\Rule; | ||
| use PHPStan\Testing\RuleTestCase; | ||
| use PHPUnit\Framework\Attributes\RequiresPhp; | ||
| use const PHP_VERSION_ID; | ||
|
|
||
| /** | ||
| * @extends RuleTestCase<ReplaceCountMismatchRule> | ||
| */ | ||
| class ReplaceCountMismatchRuleTest extends RuleTestCase | ||
| { | ||
|
|
||
| protected function getRule(): Rule | ||
| { | ||
| return new ReplaceCountMismatchRule( | ||
| self::createReflectionProvider(), | ||
| new PhpVersion(PHP_VERSION_ID), | ||
| true, | ||
| true, | ||
| ); | ||
| } | ||
|
|
||
| public function testBug3889(): void | ||
| { | ||
| $this->analyse([__DIR__ . '/data/bug-3889.php'], [ | ||
| [ | ||
| 'Call to str_replace is using fewer replacements than search values.', | ||
| 12, | ||
| ], | ||
| [ | ||
| 'Call to str_ireplace is using fewer replacements than search values.', | ||
| 36, | ||
| ], | ||
| [ | ||
| 'Call to str_replace is using fewer replacements than search values.', | ||
| 40, | ||
| '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%</>.', | ||
| ], | ||
| [ | ||
| 'Call to preg_replace is using fewer replacements than search values.', | ||
| 46, | ||
| ], | ||
| [ | ||
| 'Call to preg_filter is using fewer replacements than search values.', | ||
| 49, | ||
| ], | ||
| ]); | ||
| } | ||
|
|
||
| #[RequiresPhp('>= 8.0')] | ||
| public function testNamedArgs(): void | ||
| { | ||
| $this->analyse([__DIR__ . '/data/bug-3889-named-args.php'], [ | ||
| [ | ||
| 'Call to str_replace is using fewer replacements than search values.', | ||
| 9, | ||
| ], | ||
| ]); | ||
| } | ||
|
|
||
| } |
11 changes: 11 additions & 0 deletions
11
tests/PHPStan/Rules/Functions/data/bug-3889-named-args.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| <?php // lint >= 8.0 | ||
|
|
||
| declare(strict_types = 1); | ||
|
|
||
| namespace Bug3889NamedArgs; | ||
|
|
||
| function doFoo(string $s): void | ||
| { | ||
| str_replace(search: ['a', 'b'], subject: $s, replace: ['x']); | ||
| str_replace(search: ['a', 'b'], subject: $s, replace: ['x', 'y']); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| <?php declare(strict_types = 1); | ||
|
|
||
| namespace Bug3889; | ||
|
|
||
| class HelloWorld | ||
| { | ||
| public function sayHello(): void | ||
| { | ||
| $str = 'Hello'; | ||
| $search = ['a', 'b', 'c']; | ||
| $replace = ['x', 'y']; | ||
| echo str_replace($search, $replace, $str); | ||
| } | ||
|
|
||
| public function replaceIsString(): void | ||
| { | ||
| $str = 'Hello'; | ||
| $search = ['a', 'b', 'c']; | ||
| echo str_replace($search, 'foo', $str); | ||
| } | ||
| } | ||
|
|
||
| class Variants | ||
| { | ||
| /** | ||
| * @param list<string> $list | ||
| * @param non-empty-list<string> $nonEmptyList | ||
| * @param array{string, string} $two | ||
| * @param array{string, string, string}|array{string} $oneOrThree | ||
| */ | ||
| public function doFoo(string $s, array $list, array $nonEmptyList, array $two, array $oneOrThree): void | ||
| { | ||
| str_replace(['a', 'b'], ['x', 'y'], $s); | ||
| str_replace(['a', 'b'], ['x', 'y', 'z'], $s); | ||
| str_replace(['a', 'b'], [], $s); | ||
| str_ireplace(['a', 'b', 'c'], ['x'], $s); | ||
| str_replace('a', 'x', $s); | ||
| str_replace($list, ['x'], $s); | ||
| str_replace($nonEmptyList, ['x'], $s); | ||
| str_replace($two, ['x'], $s); | ||
| str_replace($two, $nonEmptyList, $s); | ||
| str_replace($oneOrThree, ['x'], $s); | ||
| str_replace($oneOrThree, [], $s); | ||
| str_replace(['a', 'b', 'c'], $oneOrThree, $s); | ||
|
|
||
| preg_replace(['/a/', '/b/'], ['x'], $s); | ||
| preg_replace(['/a/', '/b/'], ['x', 'y'], $s); | ||
| preg_replace(['/a/', '/b/'], 'x', $s); | ||
| preg_filter(['/a/', '/b/'], ['x'], $s); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
check the args count instead and do so very early in the method - because its fast
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I made all three changes staabm asked for in three local commits (not pushed).
make tests,make phpstanandmake csall pass.fbd86667f): the rule now returns at the very start ofprocessNode()when the call has fewer than two arguments, before looking up the function. I kept the existing key check after the arguments are reordered. With named arguments that leave outsearchorreplace, the reordered list can have a gap at position 0 or 1, and a plain count wouldn't catch that.75d824b6f): every reported call now usesargument.replaceCount. ThestrReplace/pregReplacenames per function are gone, soFUNCTIONSis now just a lookup list.0bcc27082): the message is nowCall to %s is using fewer replacements than search values., filled with the function name (e.g.Call to str_replace is using …). That made the parameter-name lookup and the size output unused, so I removed them, and updated the expected messages inReplaceCountMismatchRuleTest.The PR description still shows the old message and the
strReplace.replaceCount/pregReplace.replaceCountidentifiers, so it should be updated when these are pushed.