Add support for sorting by includes param. (#36215)

This commit is contained in:
Vedanshu Jain 2023-01-05 22:17:14 +05:30 committed by GitHub
commit 677896c304
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 56 additions and 1 deletions

View File

@ -0,0 +1,4 @@
Significance: patch
Type: fix
Add support for sorting by includes param.

View File

@ -509,8 +509,17 @@ class OrdersTableQuery {
return;
}
// No need to sanitize, will be processed in calling function.
if ( 'include' === $orderby || 'post__in' === $orderby ) {
return;
}
if ( is_string( $orderby ) ) {
$orderby = array( $orderby => $order );
$orderby_fields = array_map( 'trim', explode( ' ', $orderby ) );
$orderby = array();
foreach ( $orderby_fields as $field ) {
$orderby[ $field ] = $order;
}
}
$this->args['orderby'] = array();
@ -972,6 +981,16 @@ class OrdersTableQuery {
return;
}
if ( 'include' === $orderby || 'post__in' === $orderby ) {
$ids = $this->args['id'] ?? $this->args['includes'];
if ( empty( $ids ) ) {
return;
}
$ids = array_map( 'absint', $ids );
$this->orderby = array( "FIELD( {$this->tables['orders']}.id, " . implode( ',', $ids ) . ' )' );
return;
}
$orderby_array = array();
foreach ( $this->args['orderby'] as $_orderby => $order ) {
$orderby_array[] = "{$_orderby} {$order}";

View File

@ -1349,6 +1349,38 @@ class OrdersTableDataStoreTests extends WC_Unit_Test_Case {
);
}
/**
* @testDox Ensure sorting by `includes` param works as expected.
*/
public function test_cot_query_sort_includes() {
$this->disable_cot_sync();
$order_1 = new WC_Order();
$this->switch_data_store( $order_1, $this->sut );
$order_1->save();
$order_2 = new WC_Order();
$this->switch_data_store( $order_2, $this->sut );
$order_2->save();
$query = new OrdersTableQuery(
array(
'orderby' => 'include',
'includes' => array( $order_1->get_id(), $order_2->get_id() ),
)
);
$orders_array = $query->orders;
$this->assertEquals( array( $order_1->get_id(), $order_2->get_id() ), array( $orders_array[0], $orders_array[1] ) );
$query = new OrdersTableQuery(
array(
'orderby' => 'include',
'includes' => array( $order_2->get_id(), $order_1->get_id() ),
)
);
$orders_array = $query->orders;
$this->assertEquals( array( $order_2->get_id(), $order_1->get_id() ), array( $orders_array[0], $orders_array[1] ) );
}
/**
* @testDox Ensure search works as expected on updated orders.
*/