[filter_key => meta_key]]. */ final class MetaQueryHandler implements QueryHandlerInterface { /** * The map that defines which filter key corresponds to which meta key for each entity type. * e.g., ['ads']['type'] => '_adpresso_ad_type' * @var array */ private array $map; /** * Constructor. * * @param array $map The mapping configuration. */ public function __construct( array $map ) { $this->map = $map; } /** * Checks if this handler supports a given filter key for a specific entity type * by looking it up in its configuration map. * * @param string $key The filter key from the REST request (e.g., 'type'). * @param string $entity_type The entity type being queried ('ads', 'groups', 'placements'). * * @return bool */ public function supports( string $key, string $entity_type ): bool { return isset( $this->map[ $entity_type ][ $key ] ); } /** * Applies the meta query to the WP_Query arguments. * * @param array $query_args The current array of WP_Query arguments. * @param mixed $value The value from the REST request (can be a string or an array). * @param string $entity_type The entity type being queried. * * @return array The modified array of WP_Query arguments. */ public function apply( array $query_args, mixed $value, string $entity_type ): array { if ( empty( $value ) ) { return $query_args; } // Find our filter key (e.g. 'type') by value among the keys we map; a resolved // key is consumed so an equal value on another mapped key resolves to that one. $filter_key = null; if ( ! empty( $query_args['filters'] ) && is_array( $query_args['filters'] ) ) { foreach ( $query_args['filters'] as $key => $val ) { if ( $val === $value && $this->supports( (string) $key, $entity_type ) ) { $filter_key = $key; unset( $query_args['filters'][ $key ] ); break; } } } if ( ! $filter_key ) { // Couldn't find a matching filter key.' return $query_args; } // Fetch the database meta key from the map based on the filter key. $meta_key = $this->map[ $entity_type ][ $filter_key ] ?? null; if ( ! $meta_key ) { return $query_args; } $sanitized_values = is_array( $value ) ? array_map( 'sanitize_text_field', $value ) : sanitize_text_field( $value ); $compare_operator = is_array( $sanitized_values ) ? 'IN' : '='; if ( ! isset( $query_args['meta_query'] ) ) { $query_args['meta_query'] = []; } if ( count( $query_args['meta_query'] ) > 0 && ! isset( $query_args['meta_query']['relation'] ) ) { $query_args['meta_query']['relation'] = 'AND'; } $query_args['meta_query'][] = [ 'key' => $meta_key, 'value' => $sanitized_values, 'compare' => $compare_operator, ]; return $query_args; } }