Skip to content

Commit 2e98985

Browse files
authored
Merge pull request #2615 from rodrigoprimo/direct-database-query-fix-false-positive
DB/DirectDatabaseQuery: fix false negatives when cache function names are not a function call
2 parents cb5e9e7 + 78b650d commit 2e98985

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

WordPress/Sniffs/DB/DirectDatabaseQuerySniff.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,12 @@ public function process_token( $stackPtr ) {
229229

230230
for ( $i = ( $scopeStart + 1 ); $i < $scopeEnd; $i++ ) {
231231
if ( \T_STRING === $this->tokens[ $i ]['code'] ) {
232+
$nextNonEmpty = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $i + 1 ), null, true );
233+
234+
if ( \T_OPEN_PARENTHESIS !== $this->tokens[ $nextNonEmpty ]['code'] ) {
235+
continue;
236+
}
237+
232238
$content = strtolower( $this->tokens[ $i ]['content'] );
233239

234240
if ( isset( $this->cacheDeleteFunctions[ $content ] ) ) {

WordPress/Tests/DB/DirectDatabaseQueryUnitTest.1.inc

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,3 +354,28 @@ function cache_custom_mixed_case_B() {
354354
// phpcs:set WordPress.DB.DirectDatabaseQuery customCacheGetFunctions[]
355355
// phpcs:set WordPress.DB.DirectDatabaseQuery customCacheSetFunctions[]
356356
// phpcs:set WordPress.DB.DirectDatabaseQuery customCacheDeleteFunctions[]
357+
358+
// Protect against false negatives where the cache function names are used as the content
359+
// of a T_STRING token that is not a function call.
360+
function notCacheFunctionCalls() {
361+
global $wpdb;
362+
363+
$bar->wp_cache_get = 'something';
364+
$listofthings = $wpdb->get_col( 'SELECT something FROM somewhere WHERE someotherthing = 1' ); // Warning x 2.
365+
$foo = wp_cache_set;
366+
367+
return $listofthings;
368+
}
369+
370+
// The sniff deliberately does not distinguish between calls to cache functions and calls to methods with the same name as the functions,
371+
// as those method calls are likely custom cache functions.
372+
function methodNamesSameAsCacheFunctions() {
373+
global $wpdb, $bar;
374+
375+
if ( ! ( $listofthings = $bar->wp_cache_get( 'foo' ) ) ) {
376+
$listofthings = $wpdb->get_col( 'SELECT something FROM somewhere WHERE someotherthing = 1' ); // Warning direct DB call.
377+
$bar->wp_cache_set( 'foo', $listofthings );
378+
}
379+
380+
return $listofthings;
381+
}

WordPress/Tests/DB/DirectDatabaseQueryUnitTest.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,8 @@ public function getWarningList( $testFile = '' ) {
9797
333 => 2,
9898
343 => 1,
9999
350 => 1,
100+
364 => 2,
101+
376 => 1,
100102
);
101103
default:
102104
return array();

0 commit comments

Comments
 (0)