Fix #757: Incorrect warning when using functions that return a reference #4895
+154
−7
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.
Summary
When a function or method is declared to return by reference (e.g.
public function &getString(): string), its return value is a valid lvalue that can be passed to a by-reference parameter. PHPStan was incorrectly reporting "expects variables only" for these cases.Changes
callReturnsByReference()private method tosrc/Rules/FunctionCallParametersCheck.phpthat checks if an argument expression is a call to a function/method that returns by referenceMethodCall,StaticCall, andFuncCallAST node typesReflectionProviderintoFunctionCallParametersCheckconstructor for resolving function reflections (method reflections are resolved viaScope::getMethodReflection())FunctionCallParametersCheckto pass the newReflectionProviderparameterFunctionCallParametersCheckpatternsRoot cause
FunctionCallParametersCheckonly allowed variables, array dim fetches, property fetches, and static property fetches as valid by-reference arguments. It did not consider that function/method calls returning by reference also produce valid lvalues. The fix checks the called function/method'sreturnsByReference()reflection before reporting the error.Test
Added
tests/PHPStan/Rules/Functions/data/bug-757.phpwith test cases covering:Fixes phpstan/phpstan#757