Skip to content

Commit

Permalink
Add defensive coding to posts per page sniff and add tests
Browse files Browse the repository at this point in the history
The posts per page sniff should bail out early if empty string is passed as a value.

The tests were added for both posts per page sniff and slow db query sniff,
to check if empty string is passed as a value.
In the case of SlowDBQuery the sniff should flag cases where there is and isn't a value passed,
as that sniff will always flag whenever meta_key and meta_value are used in a query.
  • Loading branch information
dingo-d committed Sep 18, 2023
1 parent e6b3033 commit f9c2e8f
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions WordPress/Sniffs/DB/SlowDBQuerySniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace WordPressCS\WordPress\Sniffs\DB;

use PHPCSUtils\Utils\TextStrings;
use WordPressCS\WordPress\AbstractArrayAssignmentRestrictionsSniff;

/**
Expand Down
4 changes: 4 additions & 0 deletions WordPress/Sniffs/WP/PostsPerPageSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ public function getGroups() {
public function callback( $key, $val, $line, $group ) {
$stripped_val = TextStrings::stripQuotes( $val );

if ( '' === $stripped_val ) {
return false;
}

if ( $val !== $stripped_val ) {
// The value was a text string. For text strings, we only accept purely numeric values.
if ( preg_match( '`^[0-9]+$`', $stripped_val ) !== 1 ) {
Expand Down
4 changes: 4 additions & 0 deletions WordPress/Tests/DB/SlowDBQueryUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,7 @@ $query = 'foo=bar&meta_key=foo&meta_value=bar';
if ( ! isset( $widget['params'][0] ) ) {
$widget['params'][0] = array();
}

$query = 'foo=bar&meta_key=&meta_value=bar';
$query = 'foo=bar&meta_key=foo&meta_value=';
$query = 'foo=bar&meta_key=&meta_value=';
3 changes: 3 additions & 0 deletions WordPress/Tests/DB/SlowDBQueryUnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ public function getWarningList() {
15 => 1,
16 => 1,
19 => 2,
25 => 2,
26 => 2,
27 => 2,
);
}
}
14 changes: 14 additions & 0 deletions WordPress/Tests/WP/PostsPerPageUnitTest.inc
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,17 @@ $args = array(
'posts_per_page' => 75.0, // OK (75).
'posts_per_page' => 150.000, // Bad (150).
);

$query = 'posts_per_page=' . (int) $_POST['limit']; // OK.

$args = array(
'posts_per_page' => '', // OK.
);

_query_posts( 'nopaging=true&posts_per_page=' ); // OK.

$query_args['posts_per_page'] = ''; // OK.

$query_args[
'posts_per_page'
] = ''; // OK.

0 comments on commit f9c2e8f

Please sign in to comment.