diff --git a/WordPressVIPMinimum/Sniffs/Hooks/PreGetPostsSniff.php b/WordPressVIPMinimum/Sniffs/Hooks/PreGetPostsSniff.php index 8beca64f..655bbdae 100644 --- a/WordPressVIPMinimum/Sniffs/Hooks/PreGetPostsSniff.php +++ b/WordPressVIPMinimum/Sniffs/Hooks/PreGetPostsSniff.php @@ -304,9 +304,36 @@ 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 ) { + // This may be an inline control structure (no braces). + $next = $this->phpcsFile->findNext( + Tokens::$emptyTokens, + ( $nestedParenthesisEnd + 1 ), + null, + true + ); + + if ( false !== $next && T_RETURN === $this->tokens[ $next ]['code'] ) { + return true; + } + + return false; } $next = $this->phpcsFile->findNext( diff --git a/WordPressVIPMinimum/Tests/Hooks/PreGetPostsUnitTest.inc b/WordPressVIPMinimum/Tests/Hooks/PreGetPostsUnitTest.inc index 6ff848b1..09c5f06e 100644 --- a/WordPressVIPMinimum/Tests/Hooks/PreGetPostsUnitTest.inc +++ b/WordPressVIPMinimum/Tests/Hooks/PreGetPostsUnitTest.inc @@ -90,3 +90,29 @@ 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' ); + } +} + +add_action('pre_get_posts', 'inline_control_structures', 10, 1); + +function inline_control_structures( $query ) { + if( !$query->is_main_query() && !is_front_page()) return; + if(is_single() || is_search() || is_archive()) return; + + $query->set('meta_query', 'foo'); + return $query; +}