Skip to content

Commit 46895e9

Browse files
committed
PreGetPosts: improve the isEarlyMainQueryCheck() method [1]
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
1 parent ad76879 commit 46895e9

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

WordPressVIPMinimum/Sniffs/Hooks/PreGetPostsSniff.php

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -304,9 +304,24 @@ private function isEarlyMainQueryCheck( $stackPtr ) {
304304
return false;
305305
}
306306

307-
$nestedParenthesisEnd = array_shift( $this->tokens[ $stackPtr ]['nested_parenthesis'] );
308-
if ( true === in_array( 'PHPCS_T_CLOSURE', $this->tokens[ $stackPtr ]['conditions'], true ) ) {
309-
$nestedParenthesisEnd = array_shift( $this->tokens[ $stackPtr ]['nested_parenthesis'] );
307+
$parentheses = $this->tokens[ $stackPtr ]['nested_parenthesis'];
308+
do {
309+
$nestedParenthesisEnd = array_shift( $parentheses );
310+
if ( null === $nestedParenthesisEnd ) {
311+
// Nothing left in the array. No parenthesis found with a non-closure owner.
312+
return false;
313+
}
314+
315+
if ( isset( $this->tokens[ $nestedParenthesisEnd ]['parenthesis_owner'] )
316+
&& T_CLOSURE !== $this->tokens[ $this->tokens[ $nestedParenthesisEnd ]['parenthesis_owner'] ]['code']
317+
) {
318+
break;
319+
}
320+
} while ( true );
321+
322+
$owner = $this->tokens[ $nestedParenthesisEnd ]['parenthesis_owner'];
323+
if ( isset( $this->tokens[ $owner ]['scope_opener'], $this->tokens[ $owner ]['scope_closer'] ) === false ) {
324+
return false;
310325
}
311326

312327
$next = $this->phpcsFile->findNext(

WordPressVIPMinimum/Tests/Hooks/PreGetPostsUnitTest.inc

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,3 +90,19 @@ add_action( 'pre_get_posts', function( $wp_query ) {
9090
}
9191

9292
} );
93+
94+
class undefined_index_issue_499 {
95+
96+
public function __construct() {
97+
add_action( 'pre_get_posts', array( $this, 'pre_get_posts_499' ) );
98+
}
99+
100+
public function pre_get_posts_499( $wp_query ) {
101+
102+
if ( function() { return ( $wp_query->is_main_query() === false ) }() === false ) {
103+
return;
104+
}
105+
106+
$wp_query->set( 'cat', '-5' );
107+
}
108+
}

0 commit comments

Comments
 (0)