Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sniff::is_in_isset_or_empty(): improve code-style independence #1468

Merged
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
3 changes: 2 additions & 1 deletion WordPress/Sniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -1505,7 +1505,8 @@ protected function is_in_isset_or_empty( $stackPtr ) {
end( $nested_parenthesis );
$open_parenthesis = key( $nested_parenthesis );

return \in_array( $this->tokens[ ( $open_parenthesis - 1 ) ]['code'], array( \T_ISSET, \T_EMPTY ), true );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So when looking for code-style assumptions, a good starting point is $this->tokens[ $var +/- X ]?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes and no. doing that calculation is very common and correct when it's to set the starting point for a findNext()/findPrevious() function call.
Code style assumptions are only problematic for best practice sniffs, not code style sniffs and to bypass those assumption you need to take every crappy way of writing PHP into account, so looking for checks using T_WHITESPACE is another typical search entry point. This should - for code style independence - be Tokens::$emptyTokens.

$previous_non_empty = $this->phpcsFile->findPrevious( Tokens::$emptyTokens, ( $open_parenthesis - 1 ), null, true, null, true );
return in_array( $this->tokens[ $previous_non_empty ]['code'], array( \T_ISSET, \T_EMPTY ), true );
}

/**
Expand Down
15 changes: 15 additions & 0 deletions WordPress/Tests/Security/ValidatedSanitizedInputUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,18 @@ EOD

if ( ( $_POST['foo'] ?? 'post' ) === 'post' ) {} // OK.
if ( ( $_POST['foo'] <=> 'post' ) === 0 ) {} // OK.

// Test whitespace independent isset/empty detection.
function foobar() {
if ( ! isset ($_GET['test']) ) {
return ;
}
echo sanitize_text_field( wp_unslash( $_GET['test'] ) ); // OK.
}

function barfoo() {
if ( empty ($_GET['test']) ) {
return ;
}
echo sanitize_text_field( wp_unslash( $_GET['test'] ) ); // OK.
}