Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accept named meta_query clauses #3469

Merged
merged 4 commits into from
May 23, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Introduce orderby meta types + small tests refactor
  • Loading branch information
felipeelia committed May 22, 2023
commit 4c4862dbf943310f2093a0fb19475bb5f14e7d8e
82 changes: 62 additions & 20 deletions includes/classes/Indexable/Post/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -1215,8 +1215,6 @@ protected function parse_order( $order ) {
* @return array
*/
protected function parse_orderby( $orderbys, $default_order, $args ) {
global $wpdb;

$orderbys = $this->get_orderby_array( $orderbys );

$from_to = [
Expand Down Expand Up @@ -1252,26 +1250,10 @@ protected function parse_orderby( $orderbys, $default_order, $args ) {
$order = 'asc';
}

if ( in_array( $orderby_clause, [ 'meta_value', 'meta_value_num' ], true ) ) {
if ( empty( $args['meta_key'] ) ) {
continue;
} else {
$from_to['meta_value'] = 'meta.' . $args['meta_key'] . '.raw';
$from_to['meta_value_num'] = 'meta.' . $args['meta_key'] . '.long';
}
}

if ( ! empty( $from_to[ $orderby_clause ] ) ) {
$orderby_clause = $from_to[ $orderby_clause ];
} elseif ( ! empty( $args['meta_query'] ) ) {
$meta_query = new \WP_Meta_Query( $args['meta_query'] );
// Calling get_sql() to populate the WP_Meta_Query->clauses attribute
$meta_query->get_sql( 'post', $wpdb->posts, 'ID' );

$clauses = $meta_query->get_clauses();
if ( ! empty( $clauses[ $orderby_clause ] ) ) {
$orderby_clause = 'meta.' . $clauses[ $orderby_clause ]['key'] . '.value.sortable';
}
} else {
$orderby_clause = $this->parse_orderby_meta_fields( $orderby_clause, $args );
}

$sort[] = array(
Expand All @@ -1284,6 +1266,66 @@ protected function parse_orderby( $orderbys, $default_order, $args ) {
return $sort;
}

/**
* Try to parse orderby meta fields
*
* @since 4.6.0
* @param string $orderby_clause Current orderby value
* @param array $args Query args
* @return string New orderby value
*/
protected function parse_orderby_meta_fields( $orderby_clause, $args ) {
global $wpdb;

$from_to_metatypes = [
'num' => 'long',
'numeric' => 'long',
'binary' => 'value.sortable',
'char' => 'value.sortable',
'date' => 'date',
'datetime' => 'datetime',
'decimal' => 'double',
'signed' => 'long',
'time' => 'time',
'unsigned' => 'long',
];

if ( preg_match( '/^meta_value_?(.*)/', $orderby_clause, $match_type ) ) {
$meta_type = $from_to_metatypes[ strtolower( $match_type[1] ) ] ?? 'value.sortable';
}

if ( ! empty( $args['meta_key'] ) ) {
$meta_field = $args['meta_key'];
}

if ( ! isset( $meta_type ) || ! isset( $meta_field ) && ! empty( $args['meta_query'] ) ) {
$meta_query = new \WP_Meta_Query( $args['meta_query'] );
// Calling get_sql() to populate the WP_Meta_Query->clauses attribute
$meta_query->get_sql( 'post', $wpdb->posts, 'ID' );

$clauses = $meta_query->get_clauses();

if ( ! empty( $clauses[ $orderby_clause ] ) ) {
$meta_field = $clauses[ $orderby_clause ]['key'];
$clause_meta_type = strtolower( $clauses[ $orderby_clause ]['type'] );
} else {
$primary_clause = reset( $clauses );
$meta_field = $primary_clause['key'];
$clause_meta_type = strtolower( $primary_clause['type'] ?? $primary_clause['cast'] );
}

if ( ! isset( $meta_type ) ) {
$meta_type = $from_to_metatypes[ $clause_meta_type ] ?? 'value.sortable';
}
}

if ( isset( $meta_type ) && isset( $meta_field ) ) {
$orderby_clause = "meta.{$meta_field}.{$meta_type}";
}

return $orderby_clause;
}

/**
* Get Order by args Array
*
Expand Down
201 changes: 174 additions & 27 deletions tests/php/indexables/TestPost.php
Original file line number Diff line number Diff line change
Expand Up @@ -6641,41 +6641,128 @@ public function testFormatArgsEpPostFilter() {
}

/**
* Tests additional order by parameters in parse_orderby().
* Data provider for the testParseOrderby method.
*
* @return void
* @since 4.6.0
* @return array
*/
public function parseOrderbyDataProvider() {
return [
[ 'type', 'post_type.raw' ],
[ 'modified', 'post_modified' ],
[ 'relevance', '_score' ],
[ 'date', 'post_date' ],
[ 'name', 'post_name.raw' ],
[ 'title', 'post_title.sortable' ],
];
}

/**
* Test the parse_orderby() method (without meta values)
*
* @param string $orderby Orderby value
* @param string $es_key The related ES field
* @dataProvider parseOrderbyDataProvider
* @group post
*/
public function testParseOrderBy() {
public function testParseOrderby( $orderby, $es_key ) {
$method_executed = false;

// Post type.
$query_args = [
'ep_integrate' => true,
'orderby' => 'type',
'orderby' => $orderby,
'order' => 'asc',
];

$assert_callback = function( $args ) {
$assert_callback = function( $args ) use ( &$method_executed, $es_key ) {
$method_executed = true;

$this->assertArrayHasKey( 'post_type.raw', $args['sort'][0] );
$this->assertSame( 'asc', $args['sort'][0]['post_type.raw']['order'] );
$this->assertArrayHasKey( $es_key, $args['sort'][0] );
$this->assertSame( 'asc', $args['sort'][0][ $es_key ]['order'] );

return $args;
};

// We need to run tests inside a callback because parse_orderby()
// is a protected function.
// Run the tests.
add_filter( 'ep_formatted_args', $assert_callback );
$query = new \WP_Query( $query_args );
remove_filter( 'ep_formatted_args', $assert_callback );

// Post modified.
$query_args['orderby'] = 'modified';
$this->assertTrue( $method_executed );
$this->assertGreaterThanOrEqual( 1, did_filter( 'ep_formatted_args' ) );
}

$assert_callback = function( $args ) {
/**
* Data provider for following methods:
*
* - testParseOrderbyMetaValueParams
* - testParseOrderbyMetaValueWithoutMetaKeyParams
* - testParseOrderbyMetaQueryTypes
*
* @since 4.6.0
* @return array
*/
public function parseOrderbyMetaDataProvider() {
$numeric = [ 2, 1, 3 ];
$char = [ 'b', 'a', 'c' ];

$timestamps = [
strtotime( '2 days ago' ),
strtotime( '5 days ago' ),
strtotime( '1 days ago' ),
];

$date = [ gmdate( 'Y-m-d', $timestamps[0] ), gmdate( 'Y-m-d', $timestamps[1] ), gmdate( 'Y-m-d', $timestamps[2] ) ];
$datetime = [ gmdate( 'Y-m-d 14:00:00', $timestamps[0] ), gmdate( 'Y-m-d 10:00:00', $timestamps[0] ), gmdate( 'Y-m-d 23:30:00', $timestamps[0] ) ];
$time = [ '14:00', '10:00', '23:30' ];

return [
[ '', 'value.sortable', $char ],
[ 'NUM', 'long', $numeric ],
[ 'NUMERIC', 'long', $numeric ],
[ 'BINARY', 'value.sortable', $char ],
[ 'CHAR', 'value.sortable', $char ],
[ 'DATE', 'date', $date ],
[ 'DATETIME', 'datetime', $datetime ],
[ 'DECIMAL', 'double', [ 0.2, 0.1, 0.3 ] ],
[ 'SIGNED', 'long', $numeric ],
[ 'TIME', 'time', $time ],
[ 'UNSIGNED', 'long', $numeric ],
];
}

/**
* Test the parse_orderby_meta_fields() method when dealing with `'meta_value*'` and `'meta_key'` parameters
*
* @param string $meta_value_type Meta value type (as in WP)
* @param string $es_type Meta valye type in Elasticsearch
* @param array $meta_values Meta values for post creation
* @since 4.6.0
* @dataProvider parseOrderbyMetaDataProvider
* @group post
*/
public function testParseOrderbyMetaValueParams( $meta_value_type, $es_type, $meta_values ) {
$method_executed = false;

$posts = [];
foreach ( $meta_values as $value ) {
$posts[] = $this->ep_factory->post->create( [ 'meta_input' => [ 'custom_meta_key' => $value ] ] );
}
ElasticPress\Elasticsearch::factory()->refresh_indices();

$query_args = [
'ep_integrate' => true,
'fields' => 'ids',
'orderby' => 'meta_value' . ( $meta_value_type ? "_{$meta_value_type}" : '' ),
'order' => 'asc',
'meta_key' => 'custom_meta_key',
];

$assert_callback = function( $args ) use ( &$method_executed, $es_type ) {
$method_executed = true;

$this->assertArrayHasKey( 'post_modified', $args['sort'][0] );
$this->assertSame( 'asc', $args['sort'][0]['post_modified']['order'] );
$this->assertArrayHasKey( "meta.custom_meta_key.{$es_type}", $args['sort'][0] );
$this->assertSame( 'asc', $args['sort'][0][ "meta.custom_meta_key.{$es_type}" ]['order'] );

return $args;
};
Expand All @@ -6685,14 +6772,42 @@ public function testParseOrderBy() {
$query = new \WP_Query( $query_args );
remove_filter( 'ep_formatted_args', $assert_callback );

// Meta value.
$query_args['orderby'] = 'meta_value';
$query_args['meta_key'] = 'custom_meta_key';
$this->assertTrue( $method_executed );
$this->assertTrue( $query->elasticsearch_success );
$this->assertSame( $posts[1], $query->posts[0] );
$this->assertSame( $posts[0], $query->posts[1] );
$this->assertSame( $posts[2], $query->posts[2] );
}

$assert_callback = function( $args ) {
/**
* Test the parse_orderby_meta_fields() method when dealing with `'meta_value*'` parameters
*
* @param string $meta_value_type Meta value type (as in WP)
* @param string $es_type Meta valye type in Elasticsearch
* @since 4.6.0
* @dataProvider parseOrderbyMetaDataProvider
* @group post
*/
public function testParseOrderbyMetaValueWithoutMetaKeyParams( $meta_value_type, $es_type ) {
$method_executed = false;

$query_args = [
'ep_integrate' => true,
'orderby' => 'meta_value' . ( $meta_value_type ? "_{$meta_value_type}" : '' ),
'order' => 'asc',
'meta_query' => [
[
'key' => 'custom_meta_key',
'compare' => 'EXISTS',
],
],
];

$this->assertArrayHasKey( 'meta.custom_meta_key.raw', $args['sort'][0] );
$this->assertSame( 'asc', $args['sort'][0]['meta.custom_meta_key.raw']['order'] );
$assert_callback = function( $args ) use ( &$method_executed, $es_type ) {
$method_executed = true;

$this->assertArrayHasKey( "meta.custom_meta_key.{$es_type}", $args['sort'][0] );
$this->assertSame( 'asc', $args['sort'][0][ "meta.custom_meta_key.{$es_type}" ]['order'] );

return $args;
};
Expand All @@ -6702,14 +6817,43 @@ public function testParseOrderBy() {
$query = new \WP_Query( $query_args );
remove_filter( 'ep_formatted_args', $assert_callback );

// Meta value number.
$query_args['orderby'] = 'meta_value_num';
$query_args['meta_key'] = 'custom_price';
$this->assertTrue( $method_executed );
$this->assertGreaterThanOrEqual( 1, did_filter( 'ep_formatted_args' ) );
}

/**
* Test the parse_orderby_meta_fields() method when dealing with named meta queries
*
* @param string $meta_value_type Meta value type (as in WP)
* @param string $es_type Meta valye type in Elasticsearch
* @since 4.6.0
* @dataProvider parseOrderbyMetaDataProvider
* @group post
*/
public function testParseOrderbyMetaQueryTypes( $meta_value_type, $es_type ) {
$method_executed = false;

$assert_callback = function( $args ) {
$query_args = [
'ep_integrate' => true,
'orderby' => 'named_clause',
'order' => 'asc',
'meta_query' => [
[
'key' => 'unused_key',
'type' => 'NUMERIC',
],
'named_clause' => [
'key' => 'custom_meta_key',
'type' => $meta_value_type,
],
],
];

$this->assertArrayHasKey( 'meta.custom_price.long', $args['sort'][0] );
$this->assertSame( 'asc', $args['sort'][0]['meta.custom_price.long']['order'] );
$assert_callback = function( $args ) use ( &$method_executed, $es_type ) {
$method_executed = true;

$this->assertArrayHasKey( "meta.custom_meta_key.{$es_type}", $args['sort'][0] );
$this->assertSame( 'asc', $args['sort'][0][ "meta.custom_meta_key.{$es_type}" ]['order'] );

return $args;
};
Expand All @@ -6718,6 +6862,9 @@ public function testParseOrderBy() {
add_filter( 'ep_formatted_args', $assert_callback );
$query = new \WP_Query( $query_args );
remove_filter( 'ep_formatted_args', $assert_callback );

$this->assertTrue( $method_executed );
$this->assertGreaterThanOrEqual( 1, did_filter( 'ep_formatted_args' ) );
}

/**
Expand Down