Skip to content

Commit

Permalink
WPDBTrait: add support for nullsafe object operator
Browse files Browse the repository at this point in the history
... for method calls.

Tested via the `PreparedSQL` sniff.
  • Loading branch information
jrfnl committed Apr 22, 2022
1 parent ddedd1e commit 6a54b93
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
20 changes: 17 additions & 3 deletions WordPress/Helpers/WPDBTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use PHP_CodeSniffer\Util\Tokens;
use PHPCSUtils\BackCompat\BCFile;
use PHPCSUtils\Tokens\Collections;
use PHPCSUtils\Utils\Operators;

/**
* Helper utilities for sniffs which examine WPDB method calls.
Expand Down Expand Up @@ -68,12 +69,25 @@ protected function is_wpdb_method_call( File $phpcsFile, $stackPtr, $target_meth
null,
true
);
if ( false === $is_object_call
|| isset( Collections::objectOperators()[ $tokens[ $is_object_call ]['code'] ] ) === false
) {

if ( false === $is_object_call ) {
return false;
}

if ( isset( Collections::objectOperators()[ $tokens[ $is_object_call ]['code'] ] ) === false ) {
// Allow for when the nullsafe object operator has not been backfilled yet.
if ( \T_INLINE_THEN !== $tokens[ $is_object_call ]['code']
|| Operators::isNullsafeObjectOperator( $phpcsFile, $is_object_call ) === false
) {
return false;
}

if ( \T_INLINE_THEN === $tokens[ $is_object_call ]['code'] ) {
// Non-backfilled nullsafe object operator. Move the stackPtr one forward to the ->.
++$is_object_call;
}
}

$methodPtr = $phpcsFile->findNext( Tokens::$emptyTokens, ( $is_object_call + 1 ), null, true, null, true );
if ( false === $methodPtr ) {
return false;
Expand Down
3 changes: 3 additions & 0 deletions WordPress/Tests/DB/PreparedSQLUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -108,5 +108,8 @@ $wpdb
WPDB::prepare( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '" . foo() . "';" ); // Bad.
$wpdb->Query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '" . foo() . "';" ); // Bad.

$wpdb?->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '" . (int) $foo . "';" ); // OK.
$wpdb?->query( "SELECT * FROM $wpdb->posts WHERE post_title LIKE '" . foo() . "';" ); // Bad.

// Don't throw an error during live coding.
wpdb::prepare( "SELECT * FROM $wpdb->posts
1 change: 1 addition & 0 deletions WordPress/Tests/DB/PreparedSQLUnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public function getErrorList() {
106 => 1,
108 => 1,
109 => 1,
112 => 1,
);
}

Expand Down

0 comments on commit 6a54b93

Please sign in to comment.