Fix "doing wrong wpdb::prepare" notice for REST API get taxes endpoint.

This commit is contained in:
Nestor Soriano 2021-03-31 12:09:20 +02:00
parent b5e13bd771
commit 8ff664e758
No known key found for this signature in database
GPG Key ID: 08110F3518C12CAD
2 changed files with 53 additions and 7 deletions

View File

@ -243,12 +243,17 @@ class WC_REST_Taxes_V1_Controller extends WC_REST_Controller {
LIMIT %%d, %%d
";
$wpdb_prepare_args = array(
$prepared_args['offset'],
$prepared_args['number'],
);
// Filter by tax class.
if ( empty( $prepared_args['class'] ) ) {
$class = null;
$query = sprintf( $query, '' );
} else {
$class = 'standard' !== $prepared_args['class'] ? sanitize_title( $prepared_args['class'] ) : '';
array_unshift( $wpdb_prepare_args, $class );
$query = sprintf( $query, 'WHERE tax_rate_class = %s' );
}
@ -257,9 +262,7 @@ class WC_REST_Taxes_V1_Controller extends WC_REST_Controller {
$results = $wpdb->get_results(
$wpdb->prepare(
$query,
$prepared_args['offset'],
$prepared_args['number'],
$class
$wpdb_prepare_args
)
);
// phpcs:enable WordPress.DB.PreparedSQL.NotPrepared
@ -282,9 +285,7 @@ class WC_REST_Taxes_V1_Controller extends WC_REST_Controller {
$wpdb->get_results(
$wpdb->prepare(
$query,
$prepared_args['offset'],
$prepared_args['number'],
$class
$wpdb_prepare_args
)
);
// phpcs:enable WordPress.DB.PreparedSQL.NotPrepared

View File

@ -238,4 +238,49 @@ class WC_REST_Taxes_Controller_Tests extends WC_REST_Unit_Test_Case {
}
$this->assertEquals( $expected, $ids );
}
/**
* @testdox Tax rates can be queries filtering by tax class.
*
* @testWith ["standard"]
* ["reduced-rate"]
* ["zero-rate"]
*
* @param string $class The tax class name to try getting the taxes for.
*/
public function test_can_get_taxes_filtering_by_class( $class ) {
$classes = array( 'standard', 'reduced-rate', 'zero-rate' );
$tax_ids_by_class = array();
foreach ( $classes as $class ) {
$tax_id = WC_Tax::_insert_tax_rate(
array(
'tax_rate_country' => 'JP',
'tax_rate' => '1',
'tax_rate_priority' => 1,
'tax_rate_name' => 'Fake Tax',
'tax_rate_class' => $class,
)
);
$tax_ids_by_class[ $class ] = $tax_id;
}
$response = $this->do_rest_get_request(
'taxes',
array(
'class' => $class,
)
);
$this->assertEquals( 200, $response->get_status() );
$data = array_values( $response->get_data() );
$ids = array_map(
function( $item ) {
return $item['id'];
},
$data
);
$this->assertEquals( array( $tax_ids_by_class[ $class ] ), $ids );
}
}