Skip to content

DB/PreparedSQL and DB/PreparedSQLPlaceholders: false positive for static method calls to non-global classes named wpdb #2710

Description

@rodrigoprimo

Bug Description

The WordPress.DB.PreparedSQL and the WordPress.DB.PreparedSQLPlaceholders sniffs produce false positives when a static method call to a class named wpdb is preceded by a namespace.

The root cause is in WPDBTrait::is_wpdb_method_call(), which does not verify whether the T_STRING('wpdb') token is preceded by a namespace separator, which would indicate it is not the global wpdb class.

I plan to create a PR to fix this issue.

Minimal Code Snippet

The issue happens when running this command:

phpcs --standard=WordPress --sniffs=WordPress.DB.PreparedSQL,WordPress.DB.PreparedSQLPlaceholders test.php

... over a file containing this code:

<?php

$sql1 = MyNamespace\WPDB::prepare( "SELECT * FROM wp_posts WHERE post_title LIKE '" . $foo . "';" );
$sql2 = MyNamespace\wpdb::prepare( "SELECT * FROM $wpdb->users WHERE id = %d AND user_login = %s" );

Expected behavior:

No errors. This is not a call to the global $wpdb object.

Actual behavior:

FILE: test.php
---------------------------------------------------------------------------
FOUND 1 ERRORS AFFECTING 1 LINES
---------------------------------------------------------------------------
 3 | ERROR | Use placeholders and $wpdb->prepare(); found $foo
   |       | (WordPress.DB.PreparedSQL.NotPrepared)
---------------------------------------------------------------------------

Error Code

WordPress.DB.PreparedSQL.NotPrepared and WordPress.DB.PreparedSQLPlaceholders.MissingReplacements

Environment

Question Answer
PHP version 8.5.3
PHP_CodeSniffer version 3.13.5
WordPressCS version develop
PHPCSUtils version 1.2.1
PHPCSExtra version 1.5.0
WordPressCS install type git clone
IDE (if relevant) N/A

Tested Against develop Branch?

  • I have verified the issue still exists in the develop branch of WordPressCS.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions