Skip to content

Commit

Permalink
Merge pull request #564 from Automattic/fix/358-pregetpost-support-sh…
Browse files Browse the repository at this point in the history
…ort-arrays

Hooks/PreGetPosts: add support for hook-ins using short arrays
  • Loading branch information
GaryJones authored Jul 29, 2020
2 parents b0c949f + 6b6cf10 commit 8ff3fa9
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 9 deletions.
11 changes: 9 additions & 2 deletions WordPressVIPMinimum/Sniffs/Hooks/PreGetPostsSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,9 @@ public function process_token( $stackPtr ) {

if ( 'PHPCS_T_CLOSURE' === $this->tokens[ $callbackPtr ]['code'] ) {
$this->processClosure( $callbackPtr );
} elseif ( 'T_ARRAY' === $this->tokens[ $callbackPtr ]['type'] ) {
} elseif ( T_ARRAY === $this->tokens[ $callbackPtr ]['code']
|| T_OPEN_SHORT_ARRAY === $this->tokens[ $callbackPtr ]['code']
) {
$this->processArray( $callbackPtr );
} elseif ( true === in_array( $this->tokens[ $callbackPtr ]['code'], Tokens::$stringTokens, true ) ) {
$this->processString( $callbackPtr );
Expand All @@ -93,9 +95,14 @@ public function process_token( $stackPtr ) {
*/
private function processArray( $stackPtr ) {

$open_close = $this->find_array_open_close( $stackPtr );
if ( false === $open_close ) {
return;
}

$previous = $this->phpcsFile->findPrevious(
Tokens::$emptyTokens,
$this->tokens[ $stackPtr ]['parenthesis_closer'] - 1,
$open_close['closer'] - 1,
null,
true
);
Expand Down
30 changes: 30 additions & 0 deletions WordPressVIPMinimum/Tests/Hooks/PreGetPostsUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,33 @@ function inline_control_structures( $query ) {
$query->set('meta_query', 'foo');
return $query;
}

class short_array_hook_in {

public function __construct() {
add_action( 'pre_get_posts', [ $this, 'short_pre_get_posts' ] );
}

public function short_pre_get_posts( $wp_query ) {

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

if ( $wp_query->is_main_query() ) {
$wp_query->set( 'cat', '-5' );
} else if ( $wp_query->is_search() ) {
$wp_query->set( 'cat', '-5' );
}

if ( ( ! $wp_query->is_main_query() ) ) {
return;
}

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

if ( $wp_query->is_main_query() ) {
$wp_query->set( 'cat', '-5' );
} else if ( $wp_query->is_search() ) {
$wp_query->set( 'cat', '-5' );
}
}
}
16 changes: 9 additions & 7 deletions WordPressVIPMinimum/Tests/Hooks/PreGetPostsUnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,15 @@ public function getErrorList() {
*/
public function getWarningList() {
return [
8 => 1,
11 => 1,
29 => 1,
32 => 1,
52 => 1,
57 => 1,
87 => 1,
8 => 1,
11 => 1,
29 => 1,
32 => 1,
52 => 1,
57 => 1,
87 => 1,
128 => 1,
133 => 1,
];
}

Expand Down

0 comments on commit 8ff3fa9

Please sign in to comment.