Repository navigation
StrictFunctionCallsRule is auto-fixable #349
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
staabm
wants to merge
21
commits into
phpstan:2.1.x
Choose a base branch
from
staabm:autof
base: 2.1.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
21 commits
Select commit
Hold shift + click to select a range
98b96fa
StrictFunctionCallsRule is auto-fixable
staabm b014b77
add string comparison edge case
staabm f4ed7c2
test class-constants
staabm 9a7e6d4
link edge case
staabm 8f203b3
make some strings autofixable
staabm 6685908
added failling test
staabm d36fdcc
Update StrictFunctionCallsRule.php
staabm 11d068e
Update StrictFunctionCallsRule.php
staabm 7771be1
fix
staabm ee40740
Update StrictFunctionCallsRule.php
staabm 4cf7c02
fix lint
staabm 9fe0f41
test it fixes strcit=1/0 to const bool
staabm 6ee6afd
fix properties with side-effects
staabm f04d1d6
Update StrictFunctionCallsRule.php
staabm abfdd0c
test properties with side-effects
staabm 00e6af8
remove dirty hack
staabm 3332d3e
Update StrictFunctionCallsRule.php
staabm b972f1a
simplify
staabm 421227d
extract non-lint example into separate test
staabm 974d0e4
cs
staabm fa5f83c
fix name collision
staabm 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,15 +3,24 @@ | |
| namespace PHPStan\Rules\StrictCalls; | ||
|
|
||
| use PhpParser\Node; | ||
| use PhpParser\Node\Arg; | ||
| use PhpParser\Node\Expr\ConstFetch; | ||
| use PhpParser\Node\Expr\FuncCall; | ||
| use PhpParser\Node\Identifier; | ||
| use PhpParser\Node\Name; | ||
| use PhpParser\Node\Scalar; | ||
| use PHPStan\Analyser\ArgumentsNormalizer; | ||
| use PHPStan\Analyser\Scope; | ||
| use PHPStan\Reflection\ParametersAcceptor; | ||
| use PHPStan\Reflection\ParametersAcceptorSelector; | ||
| use PHPStan\Reflection\ReflectionProvider; | ||
| use PHPStan\Rules\IdentifierRuleError; | ||
| use PHPStan\Rules\Rule; | ||
| use PHPStan\Rules\RuleErrorBuilder; | ||
| use PHPStan\Type\Type; | ||
| use function array_key_exists; | ||
| use function array_search; | ||
| use function in_array; | ||
| use function sprintf; | ||
| use function strtolower; | ||
|
|
||
|
|
@@ -47,6 +56,8 @@ public function processNode(Node $node, Scope $scope): array | |
| return []; | ||
| } | ||
|
|
||
| $originalNode = $node; | ||
|
|
||
| if (!$this->reflectionProvider->hasFunction($node->name, $scope)) { | ||
| return []; | ||
| } | ||
|
|
@@ -69,26 +80,165 @@ public function processNode(Node $node, Scope $scope): array | |
| $argumentPosition = $this->functionArguments[$functionName]; | ||
| if (!array_key_exists($argumentPosition, $node->getArgs())) { | ||
| return [ | ||
| RuleErrorBuilder::message(sprintf( | ||
| 'Call to function %s() requires parameter #%d to be set.', | ||
| $this->buildError( | ||
| sprintf( | ||
| 'Call to function %s() requires parameter #%d to be set.', | ||
| $functionName, | ||
| $argumentPosition + 1, | ||
| ), | ||
| $functionName, | ||
| $argumentPosition + 1, | ||
| ))->identifier('function.strict')->build(), | ||
| $originalNode, | ||
| $node, | ||
| $scope, | ||
| $parametersAcceptor, | ||
| $argumentPosition, | ||
| ), | ||
| ]; | ||
| } | ||
|
|
||
| $argumentType = $scope->getType($node->getArgs()[$argumentPosition]->value); | ||
| if (!$argumentType->isTrue()->yes()) { | ||
| return [ | ||
| RuleErrorBuilder::message(sprintf( | ||
| 'Call to function %s() requires parameter #%d to be true.', | ||
| $this->buildError( | ||
| sprintf( | ||
| 'Call to function %s() requires parameter #%d to be true.', | ||
| $functionName, | ||
| $argumentPosition + 1, | ||
| ), | ||
| $functionName, | ||
| $argumentPosition + 1, | ||
| ))->identifier('function.strict')->build(), | ||
| $originalNode, | ||
| $node, | ||
| $scope, | ||
| $parametersAcceptor, | ||
| $argumentPosition, | ||
| ), | ||
| ]; | ||
| } | ||
|
|
||
| return []; | ||
| } | ||
|
|
||
| private function buildError( | ||
| string $message, | ||
| string $functionName, | ||
| FuncCall $originalNode, | ||
| FuncCall $normalizedNode, | ||
| Scope $scope, | ||
| ParametersAcceptor $parametersAcceptor, | ||
| int $strictArgumentPosition | ||
| ): IdentifierRuleError | ||
| { | ||
| $errorBuilder = RuleErrorBuilder::message($message)->identifier('function.strict'); | ||
| if ( | ||
| ($functionName === 'in_array' || $functionName === 'array_search' || $functionName === 'array_keys') | ||
| && $this->hasSafeStrictComparisonTypes($functionName, $normalizedNode, $scope) | ||
| ) { | ||
| $namedArgumentPositions = []; | ||
| foreach ($parametersAcceptor->getParameters() as $position => $parameter) { | ||
| $namedArgumentPositions[$parameter->getName()] = $position; | ||
| } | ||
|
|
||
| $errorBuilder->fixNode($originalNode, static function (FuncCall $call) use ($namedArgumentPositions, $strictArgumentPosition): FuncCall { | ||
| $strictArgument = null; | ||
| $hasNamedArguments = false; | ||
| $usedPositions = []; | ||
| foreach ($call->getArgs() as $arg) { | ||
| if ($arg->unpack) { | ||
| // unpack is not fixable | ||
| return $call; | ||
| } | ||
|
|
||
| if ($arg->name !== null) { | ||
| $hasNamedArguments = true; | ||
| $argumentName = $arg->name->toString(); | ||
| if (!array_key_exists($argumentName, $namedArgumentPositions)) { | ||
| return $call; | ||
| } | ||
|
|
||
| $argumentPosition = $namedArgumentPositions[$argumentName]; | ||
| $usedPositions[$argumentPosition] = true; | ||
| if ($argumentPosition === $strictArgumentPosition) { | ||
| $strictArgument = $arg; | ||
| } | ||
| continue; | ||
| } | ||
|
|
||
| $argumentPosition = 0; | ||
| while (array_key_exists($argumentPosition, $usedPositions)) { | ||
| $argumentPosition++; | ||
| } | ||
| $usedPositions[$argumentPosition] = true; | ||
| if ($argumentPosition !== $strictArgumentPosition) { | ||
| continue; | ||
| } | ||
|
|
||
| $strictArgument = $arg; | ||
| } | ||
|
|
||
| $true = new ConstFetch(new Name('true')); | ||
| if ($strictArgument !== null) { | ||
| if ( | ||
| $strictArgument->value instanceof ConstFetch | ||
| ) { | ||
| if (!in_array($strictArgument->value->name->toLowerString(), ['true', 'false', 'null'], true)) { | ||
| return $call; | ||
| } | ||
| } elseif ( | ||
| !$strictArgument->value instanceof Scalar\Int_ | ||
| && !$strictArgument->value instanceof Scalar\String_ | ||
| ) { | ||
| return $call; | ||
| } | ||
|
|
||
| $strictArgument->value = $true; | ||
| return $call; | ||
| } | ||
|
|
||
| $targetArgumentName = array_search($strictArgumentPosition, $namedArgumentPositions, true); | ||
|
|
||
| $call->args[] = new Arg( | ||
| $true, | ||
| false, | ||
| false, | ||
| [], | ||
| $hasNamedArguments && $targetArgumentName !== false ? new Identifier($targetArgumentName) : null, | ||
| ); | ||
|
|
||
| return $call; | ||
| }); | ||
| } | ||
|
|
||
| return $errorBuilder->build(); | ||
| } | ||
|
|
||
| private function hasSafeStrictComparisonTypes(string $functionName, FuncCall $normalizedNode, Scope $scope): bool | ||
| { | ||
| $args = $normalizedNode->getArgs(); | ||
| if (!isset($args[0], $args[1])) { | ||
| return false; | ||
| } | ||
|
|
||
| $needleArgument = $functionName === 'array_keys' ? $args[1] : $args[0]; | ||
| $haystackArgument = $functionName === 'array_keys' ? $args[0] : $args[1]; | ||
| $needleType = $scope->getNativeType($needleArgument->value); | ||
| $haystackValueType = $scope->getNativeType($haystackArgument->value)->getIterableValueType(); | ||
|
|
||
| return $this->areSameStrictScalarTypes($needleType, $haystackValueType); | ||
| } | ||
|
|
||
| private function areSameStrictScalarTypes(Type $needleType, Type $haystackValueType): bool | ||
| { | ||
| return ( | ||
| $needleType->isBoolean()->yes() | ||
| && $haystackValueType->isBoolean()->yes() | ||
| ) || ( | ||
| $needleType->isInteger()->yes() | ||
| && $haystackValueType->isInteger()->yes() | ||
| ) || ( | ||
| $needleType->isString()->yes() | ||
| && $haystackValueType->isString()->yes() | ||
| && $haystackValueType->isNumericString()->no() | ||
| ); | ||
| } | ||
|
Comment on lines
+229
to
+242
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. only fixing the most valuable and least risky for now |
||
|
|
||
| } | ||
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
97 changes: 97 additions & 0 deletions
97
tests/Rules/StrictCalls/data/strict-function-calls-fixable.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,97 @@ | ||
| <?php | ||
|
|
||
| namespace StrictCalls; | ||
|
|
||
| function searchBool(bool $bool) { | ||
| array_search(false, [$bool]); | ||
| } | ||
|
|
||
| in_array(1, [1, 2]); | ||
| in_array(1, [1, 2], false); | ||
| array_keys([1, 2], 1); | ||
| $strict = rand(0, 1) === 1; | ||
| array_keys([1, 2], 1, $strict); | ||
| in_array(1, [1.0]); | ||
| in_array(1, [1.0], false); | ||
| in_array(1, [1, 1.0]); | ||
| in_array('1', ['01']); | ||
|
|
||
| in_array(1, [1, 2], 1); | ||
| in_array(1, [1, 2], 0); | ||
| in_array(1, [1, 2], "1"); | ||
| in_array(1, [1, 2], "0"); | ||
|
|
||
| $float = 1.0; | ||
| in_array($float, [1.0]); | ||
| in_array(null, [null]); | ||
|
|
||
| /** @return int[] */ | ||
| function getArray(): array | ||
| { | ||
| return [1, 2]; | ||
| } | ||
|
|
||
| function doFoo(int $i): bool | ||
| { | ||
| return in_array($i, getArray()); | ||
| } | ||
|
|
||
| array_keys([1, 2]); | ||
| base64_decode('abcd'); | ||
|
|
||
| $numericStringNeedle = '01'; // edge case: numeric string compared against int-string: https://3v4l.org/hmgdd#v | ||
| in_array($numericStringNeedle, ['1', '2']); | ||
|
|
||
| $stringNeedle = 'foo'; | ||
| $strings = ['foo', 'bar']; | ||
| in_array($stringNeedle, $strings); | ||
| in_array($stringNeedle, $strings, false); | ||
| array_search($stringNeedle, $strings); | ||
| array_keys($strings, $stringNeedle); | ||
|
|
||
| /** @return string[] */ | ||
| function getStringArray(): array | ||
| { | ||
| return ['foo', 'bar']; | ||
| } | ||
|
|
||
| function doStringFoo(string $needle): bool | ||
| { | ||
| return in_array($needle, getStringArray()); | ||
| } | ||
|
|
||
| function doLiteralStringFoo(string $needle): bool | ||
| { | ||
| return in_array($needle, ['foo', 'bar']); | ||
| } | ||
|
|
||
| class X { | ||
| private const TYPES = [128, 256]; | ||
| private const TYPE_STRINGS = ['ABC', 'DEF']; | ||
| private const TYPES_NUMERIC_STRING = ['ABC', 'DEF', '1']; | ||
|
|
||
| function doFoo(int $i, string $s) { | ||
| in_array($i, self::TYPES); | ||
| in_array($s, self::TYPE_STRINGS); | ||
| in_array($s, self::TYPES_NUMERIC_STRING); | ||
| } | ||
| } | ||
|
|
||
| class SideEffectProperty { | ||
|
|
||
| public function __get(string $name): bool | ||
| { | ||
| // some side-effect | ||
| echo 'side effect'; | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| } | ||
|
|
||
| $sideEffectProperty = new SideEffectProperty(); | ||
| // the "strict" argument is an interpolated string whose embedded expression | ||
| // triggers a magic __get() with a side-effect; it must not be overwritten | ||
| // with a plain "true" because that would silently drop the side-effect. | ||
| in_array(1, [1], "{$sideEffectProperty->strict}"); | ||
|
|
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.