Skip to content

Commit

Permalink
Sniff::get_function_call_parameters(): correctly handle closures when…
Browse files Browse the repository at this point in the history
… passed as param

Closures can be declared within function calls when the function expects a call-back.
This situation was only partially handled within the `Sniff::get_function_call_parameters()` method.

Most of the time when a comma is encountered within a closure, it will be at a different nesting level than the original function call/array, which meant it would be disregarded and the method would return the correct results.
However, there are some, albeit rare, situations in which the comma would be at the target nesting level, causing the method to split the closure into two or more "parameters".

As far as I know, this bug has not caused any issues for any of the WPCS sniffs so far, but the situation should be handled correctly even so.

I came across this while working on 1371, the PR for which will contain a unit test covering this fix.

Additionally, the same fix has been pulled to the PHPCompatibility standard with dedicated unit tests.
See: PHPCompatibility/682

Related to 764
  • Loading branch information
jrfnl committed Jun 25, 2018
1 parent cca93a6 commit 83e1666
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion WordPress/Sniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -2096,7 +2096,7 @@ public function get_function_call_parameters( $stackPtr ) {
$next_comma = $opener;
$param_start = ( $opener + 1 );
$cnt = 1;
while ( $next_comma = $this->phpcsFile->findNext( array( T_COMMA, $this->tokens[ $closer ]['code'], T_OPEN_SHORT_ARRAY ), ( $next_comma + 1 ), ( $closer + 1 ) ) ) {
while ( ( $next_comma = $this->phpcsFile->findNext( array( T_COMMA, $this->tokens[ $closer ]['code'], T_OPEN_SHORT_ARRAY, T_CLOSURE ), ( $next_comma + 1 ), ( $closer + 1 ) ) ) !== false ) {
// Ignore anything within short array definition brackets.
if ( 'T_OPEN_SHORT_ARRAY' === $this->tokens[ $next_comma ]['type']
&& ( isset( $this->tokens[ $next_comma ]['bracket_opener'] )
Expand All @@ -2108,6 +2108,17 @@ public function get_function_call_parameters( $stackPtr ) {
continue;
}

// Skip past closures passed as function parameters.
if ( 'T_CLOSURE' === $this->tokens[ $next_comma ]['type']
&& ( isset( $this->tokens[ $next_comma ]['scope_condition'] )
&& $this->tokens[ $next_comma ]['scope_condition'] === $next_comma )
&& isset( $this->tokens[ $next_comma ]['scope_closer'] )
) {
// Skip forward to the end of the closure declaration.
$next_comma = $this->tokens[ $next_comma ]['scope_closer'];
continue;
}

// Ignore comma's at a lower nesting level.
if ( T_COMMA === $this->tokens[ $next_comma ]['code']
&& isset( $this->tokens[ $next_comma ]['nested_parenthesis'] )
Expand Down

0 comments on commit 83e1666

Please sign in to comment.