Skip to content

Commit

Permalink
PreGetPosts: improve the isEarlyMainQueryCheck() method
Browse files Browse the repository at this point in the history
This adds a unit test which results in the error as reported in issue 499 and fixes the error properly.

The error was caused by the presumption in the code that if an a check for `is_main_query` has a scope condition which is a `closure`, that the `closure` is the callback in the hook function call and that therefore the outer parenthesis (those of the function call) should be disgarded and the next parenthesis will be the ones for the `if` statement which will always have a scope opener and closer.

Now read the above sentence again and count the number of assumptions in that statement ;-)

Either way, the fix I've now added should stabilize this part of the code.

Fixes 499
  • Loading branch information
jrfnl committed Jul 28, 2020
1 parent 84605b5 commit 8845433
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
21 changes: 18 additions & 3 deletions WordPressVIPMinimum/Sniffs/Hooks/PreGetPostsSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -304,9 +304,24 @@ private function isEarlyMainQueryCheck( $stackPtr ) {
return false;
}

$nestedParenthesisEnd = array_shift( $this->tokens[ $stackPtr ]['nested_parenthesis'] );
if ( true === in_array( 'PHPCS_T_CLOSURE', $this->tokens[ $stackPtr ]['conditions'], true ) ) {
$nestedParenthesisEnd = array_shift( $this->tokens[ $stackPtr ]['nested_parenthesis'] );
$parentheses = $this->tokens[ $stackPtr ]['nested_parenthesis'];
do {
$nestedParenthesisEnd = array_shift( $parentheses );
if ( null === $nestedParenthesisEnd ) {
// Nothing left in the array. No parenthesis found with a non-closure owner.
return false;
}

if ( isset( $this->tokens[ $nestedParenthesisEnd ]['parenthesis_owner'] )
&& T_CLOSURE !== $this->tokens[ $this->tokens[ $nestedParenthesisEnd ]['parenthesis_owner'] ]['code']
) {
break;
}
} while ( true );

$owner = $this->tokens[ $nestedParenthesisEnd ]['parenthesis_owner'];
if ( isset( $this->tokens[ $owner ]['scope_opener'], $this->tokens[ $owner ]['scope_closer'] ) === false ) {
return false;
}

$next = $this->phpcsFile->findNext(
Expand Down
16 changes: 16 additions & 0 deletions WordPressVIPMinimum/Tests/Hooks/PreGetPostsUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,19 @@ add_action( 'pre_get_posts', function( $wp_query ) {
}

} );

class undefined_index_issue_499 {

public function __construct() {
add_action( 'pre_get_posts', array( $this, 'pre_get_posts_499' ) );
}

public function pre_get_posts_499( $wp_query ) {

if ( function() { return ( $wp_query->is_main_query() === false ) }() === false ) {
return;
}

$wp_query->set( 'cat', '-5' );
}
}

0 comments on commit 8845433

Please sign in to comment.