Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 12 additions & 9 deletions WordPressVIPMinimum/Sniffs/Hooks/PreGetPostsSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -356,16 +356,19 @@ private function isEarlyMainQueryCheck( $stackPtr ): bool {
return false;
}

$next = $this->phpcsFile->findNext(
[ T_RETURN ],
$this->tokens[ $this->tokens[ $nestedParenthesisEnd ]['parenthesis_owner'] ]['scope_opener'],
$this->tokens[ $this->tokens[ $nestedParenthesisEnd ]['parenthesis_owner'] ]['scope_closer'],
false,
'return',
true
);
// Look for a return which belongs to the control structure itself, not to anything nested inside it.
$scopeCloser = $this->tokens[ $owner ]['scope_closer'];
$return = $this->phpcsFile->findNext( T_RETURN, $this->tokens[ $owner ]['scope_opener'] + 1, $scopeCloser );
while ( $return !== false ) {
$conditionStackPtrs = array_keys( $this->tokens[ $return ]['conditions'] );
if ( array_pop( $conditionStackPtrs ) === $owner ) {
return true;
}

$return = $this->phpcsFile->findNext( T_RETURN, $return + 1, $scopeCloser );
}

return $next !== false;
return false;
}

/**
Expand Down
35 changes: 35 additions & 0 deletions WordPressVIPMinimum/Tests/Hooks/PreGetPostsUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -146,3 +146,38 @@ class short_array_hook_in {
}
}
}

// The early return does not have to be the first statement in the if. See #902.
add_action( 'pre_get_posts', function( $query ) {
if ( ! $query->is_main_query() ) {
do_log( 'x' );
return;
}
$query->set( 'cat', '-5' ); // Ok.
} );

add_action( 'pre_get_posts', function( $query ) {
if ( ! $query->is_main_query() ) {
if ( is_admin() ) {
return;
}
}
$query->set( 'cat', '-5' ); // Warning - the return is conditional.
} );

add_action( 'pre_get_posts', function( $query ) {
if ( ! $query->is_main_query() ) {
$callback = function() {
return;
};
}
$query->set( 'cat', '-5' ); // Warning - the return belongs to the nested closure.
} );

add_action( 'pre_get_posts', function( $query ) {
if ( ! $query->is_main_query() ) :
do_log( 'x' );
return;
endif;
$query->set( 'cat', '-5' ); // Ok - alternative syntax.
} );
2 changes: 2 additions & 0 deletions WordPressVIPMinimum/Tests/Hooks/PreGetPostsUnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ public function getWarningList() {
87 => 1,
128 => 1,
133 => 1,
165 => 1,
174 => 1,
];
}
}
Loading