Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
try: refactor merge_queries to take any form of input without unpacking
Browse files Browse the repository at this point in the history
and preparing the input arrays
  • Loading branch information
dinhtungdu committed Nov 24, 2022
1 parent 0f37868 commit c492ce6
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/BlockTypes/ProductQuery.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<?php
namespace Automattic\WooCommerce\Blocks\BlockTypes;

use WP_Query;

// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_tax_query
// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_query
// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key
Expand Down Expand Up @@ -135,8 +137,8 @@ public function build_query( $query ) {
return $this->merge_queries(
$common_query_values,
$this->get_custom_orderby_query( $query['orderby'] ),
...array_values( $this->get_queries_by_attributes( $parsed_block ) ),
...array_values( $this->get_queries_by_applied_filters() )
$this->get_queries_by_attributes( $parsed_block ),
$this->get_queries_by_applied_filters()
);
}

Expand All @@ -156,7 +158,7 @@ private function get_products_ids_by_attributes( $parsed_block ) {
'meta_query' => array(),
'tax_query' => array(),
),
...array_values( $this->get_queries_by_attributes( $parsed_block ) )
$this->get_queries_by_attributes( $parsed_block )
);

$products = new \WP_Query( $query );
Expand All @@ -172,9 +174,21 @@ private function get_products_ids_by_attributes( $parsed_block ) {
* @return array
*/
private function merge_queries( ...$queries ) {
$valid_query_vars = array_keys( ( new WP_Query() )->fill_query_vars( array() ) );
$valid_query_vars = array_merge(
$valid_query_vars,
array( 'meta_query', 'tax_query', 'date_query' )
);

$merged_query = array_reduce(
$queries,
function( $acc, $query ) {
function( $acc, $query ) use ( $valid_query_vars ) {
if ( ! is_array( $query ) ) {
return $acc;
}
if ( empty( array_intersect( $valid_query_vars, array_keys( $query ) ) ) ) {
return $this->merge_queries( $acc, ...array_values( $query ) );
}
return array_merge_recursive( $acc, $query );
},
array()
Expand Down

0 comments on commit c492ce6

Please sign in to comment.