Skip to content

Commit 45fd0d4

Browse files
authored
Merge pull request #565 from Automattic/fix/499-pregetposts-undefined-index-notice
2 parents ad76879 + 82d1232 commit 45fd0d4

File tree

2 files changed

+56
-3
lines changed

2 files changed

+56
-3
lines changed

WordPressVIPMinimum/Sniffs/Hooks/PreGetPostsSniff.php

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -304,9 +304,36 @@ 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+
// This may be an inline control structure (no braces).
325+
$next = $this->phpcsFile->findNext(
326+
Tokens::$emptyTokens,
327+
( $nestedParenthesisEnd + 1 ),
328+
null,
329+
true
330+
);
331+
332+
if ( false !== $next && T_RETURN === $this->tokens[ $next ]['code'] ) {
333+
return true;
334+
}
335+
336+
return false;
310337
}
311338

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

WordPressVIPMinimum/Tests/Hooks/PreGetPostsUnitTest.inc

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,3 +90,29 @@ 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+
}
109+
110+
add_action('pre_get_posts', 'inline_control_structures', 10, 1);
111+
112+
function inline_control_structures( $query ) {
113+
if( !$query->is_main_query() && !is_front_page()) return;
114+
if(is_single() || is_search() || is_archive()) return;
115+
116+
$query->set('meta_query', 'foo');
117+
return $query;
118+
}

0 commit comments

Comments
 (0)