Generic/ConstructorName: fix bug with nested anonymous classes and more #2182
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.
Based on the bug report and test case in issue #2178, I've had a look at this sniff.
Turns out the
processTokensWithinScope()
method gets called for each whitelisted scope aT_FUNCTION
token exists in.In effect, this means that the first time it gets called for the
nested()
method, it is because it is within the scope of theNested
class, the second time the function gets called, it is for the method being in the scope of the anonymous class.The fix I've now applied checks that the scope for which the method is called is actually the deepest scope first and bows out if it's not. This fixes the false positive.
Additionally, the
loadFunctionNamesInScope()
method would examine every token within the class and the resulting function list would therefore include the names of functions which were nested.This would lead to false negatives as a
__construct()
method in a nested class would be regarded as the__construct()
method of the higher level class and the expected error would not be thrown.I've fixed this by having the
loadFunctionNamesInScope()
method skip to the end of a function after adding the function name to the list, which effectively will prevent the names of nested functions from getting into the list.This should also make the method more efficient as it now examines a lot less tokens.
Additional notes:
strcasecmp()
, thein_array()
check and the check for the extended parent class name were not done in a case-insensitive manner leading - again - to incorrect results.This has now been fixed by lowercasing both the class name as well as all function names before comparing them.
in_array()
to prevent issues with type juggling.As the name of the class on line 32 was the same as the name of the class for the preceding unit test case, the function name list did not get refreshed and therefore the unit test wasn't testing things correctly.
Includes unit tests for all fixes.
Fixes #2178