Skip to content

Add negative and positive search to global search. #2015

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

Merged
merged 3 commits into from
Apr 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
107 changes: 85 additions & 22 deletions includes/widgets/search-widget/class-search-widget.php
Original file line number Diff line number Diff line change
Expand Up @@ -694,11 +694,10 @@ public function filter_entries( $search_criteria, $form_id = null, $args = array
$criteria = $this->get_criteria_from_query( $search_all_value, $split_words );

foreach ( $criteria as $criterion ) {
$search_criteria['field_filters'][] = [
'key' => $criterion['key'] ?? null, // The field ID to search
'value' => $criterion['value'], // The value to search
'operator' => $criterion['operator'], // What to search in. Options: `is` or `contains`
];
$search_criteria['field_filters'][] = array_merge(
[ 'key' => null ],
$criterion
);
}
}

Expand Down Expand Up @@ -906,7 +905,6 @@ public function gf_query_filter( &$query, $view, $request ) {
* We feed these into an new GF_Query and tack them onto the current object.
*/
$search_criteria = $this->filter_entries( array(), null, array( 'id' => $view->ID ), true /** force search_criteria */ );

/**
* Call any userland filters that they might have.
*/
Expand All @@ -920,6 +918,23 @@ public function gf_query_filter( &$query, $view, $request ) {
return;
}

$include_global_search_words = $exclude_global_search_words = [];

foreach ( $search_criteria['field_filters'] as $i => $criterion ) {
if ( ! empty( $criterion['key'] ?? null ) ) {
continue;
}

if ( 'not contains' === ( $criterion['operator'] ?? '' ) ) {
$exclude_global_search_words[] = $criterion['value'];
unset( $search_criteria['field_filters'][ $i ] );
} elseif ( true === ( $criterion['required'] ?? false ) ) {
$include_global_search_words[] = $criterion['value'];
unset( $search_criteria['field_filters'][ $i ] );
}
}


$widgets = $view->widgets->by_id( $this->widget_id );
if ( $widgets->count() ) {
$widgets = $widgets->all();
Expand Down Expand Up @@ -1113,10 +1128,53 @@ public function gf_query_filter( &$query, $view, $request ) {
*/
$query_parts = $query->_introspect();

if ( $include_global_search_words ) {
global $wpdb;
$extra_conditions[] = new GF_Query_Condition( new GF_Query_Call(
'EXISTS',
[
sprintf(
'SELECT 1 FROM `%s` WHERE `form_id` = %d AND `entry_id` = `%s`.`id` AND (%s)',
GFFormsModel::get_entry_meta_table_name(),
$view->form ? $view->form->ID : 0,
$query->_alias( null, $view->form ? $view->form->ID : 0 ),
implode( ' AND ', array_map( static function ( string $word ) use ( $wpdb ) {
return $wpdb->prepare( '`meta_value` LIKE "%%%s%%"', $word );
}, $include_global_search_words ) )
)
]
) );
}

if ( $exclude_global_search_words ) {
global $wpdb;
$extra_conditions[] = new GF_Query_Condition( new GF_Query_Call(
'NOT EXISTS',
[
sprintf(
'SELECT 1 FROM `%s` WHERE `form_id` = %d AND `entry_id` = `%s`.`id` AND (%s)',
GFFormsModel::get_entry_meta_table_name(),
$view->form ? $view->form->ID : 0,
$query->_alias( null, $view->form ? $view->form->ID : 0 ),
implode( ' OR ', array_map( static function ( string $word ) use ( $wpdb ) {
return $wpdb->prepare( '`meta_value` LIKE "%%%s%%"', $word );
}, $exclude_global_search_words ) )
)
]
) );
}


/**
* Combine the parts as a new WHERE clause.
*/
$where = call_user_func_array( '\GF_Query_Condition::_and', array_merge( array( $query_parts['where'] ), $search_conditions, $extra_conditions ) );
$where = \GF_Query_Condition::_and(
...array_merge(
[$query_parts['where']],
$search_conditions,
$extra_conditions
)
);
$query->where( $where );
}

Expand Down Expand Up @@ -2298,30 +2356,35 @@ private function get_criteria_from_query( string $query, bool $split_words ): ar
$quotation_marks = $this->get_quotation_marks();

$regex = sprintf(
'/(%s)(?<word>.*?)(%s)/m',
'/(?<match>(\+|\-))?(%s)(?<word>.*?)(%s)/m',
implode( '|', self::preg_quote( $quotation_marks['opening'] ?? [] ) ),
implode( '|', self::preg_quote( $quotation_marks['closing'] ?? [] ) )
);

if ( preg_match_all( $regex, $query, $matches ) ) {
$query = str_replace( $matches[0], '', $query );
foreach ( $matches['word'] as $exact_word ) {
$words[] = [ 'operator' => 'contains', 'value' => $exact_word ];
foreach ( $matches['word'] as $i => $value ) {
$operator = '-' === $matches['match'][ $i ] ? 'not contains' : 'contains';
$required = '+' === $matches['match'][ $i ];
$words[] = array_filter( compact( 'operator', 'value', 'required' ) );
}
}

if ( $query && $split_words ) {
foreach ( preg_split( '/\s+/', $query ) as $word ) {
$words[] = [
'operator' => 'contains',
'value' => $word,
];
}
} elseif ( $query ) {
$words[] = [
'operator' => 'contains',
'value' => preg_replace( '/\s+/', ' ', $query ),
];
$values = [];
if ( $query ) {
$values = $split_words
? preg_split( '/\s+/', $query )
: [ preg_replace( '/\s+/', ' ', $query ) ];
}

foreach ( $values as $value ) {
$is_exclude = '-' === ( $value[0] ?? '' );
$required = '+' === ( $value[0] ?? '' );
$words[] = array_filter( [
'operator' => $is_exclude ? 'not contains' : 'contains',
'value' => ( $is_exclude || $required ) ? substr( $value, 1 ) : $value,
'required' => $required,
] );
}

return array_filter( $words, static function ( array $word ) {
Expand Down
94 changes: 84 additions & 10 deletions tests/unit-tests/GravityView_Widget_Search_Test.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,17 +97,61 @@ private function _test_word_splitting() {

$_GET = [ 'gv_search' => '" space " "another one" and two' ];

$search_criteria_split_exact = [
'field_filters' => [
'mode' => 'any',
[ 'key' => null, 'value' => ' space ', 'operator' => 'contains' ],
[ 'key' => null, 'value' => 'another one', 'operator' => 'contains' ],
[ 'key' => null, 'value' => 'and', 'operator' => 'contains' ],
[ 'key' => null, 'value' => 'two', 'operator' => 'contains' ],
]
];
$this->assertEquals(
[
'field_filters' => [
'mode' => 'any',
[ 'key' => null, 'value' => ' space ', 'operator' => 'contains' ],
[ 'key' => null, 'value' => 'another one', 'operator' => 'contains' ],
[ 'key' => null, 'value' => 'and', 'operator' => 'contains' ],
[ 'key' => null, 'value' => 'two', 'operator' => 'contains' ],
]
],
$this->widget->filter_entries( array(), null, $args, true )
);

$_GET = [ 'gv_search' => '-"excluded spaces" -another' ];

$this->assertEquals(
[
'field_filters' => [
'mode' => 'any',
[ 'key' => null, 'value' => 'excluded spaces', 'operator' => 'not contains' ],
[ 'key' => null, 'value' => 'another', 'operator' => 'not contains' ],
]
],
$this->widget->filter_entries( array(), null, $args, true )
);

// Additive search
$_GET = [ 'gv_search' => 'world +"included spaces" +another hello' ];
$this->assertEquals(
[
'field_filters' => [
'mode' => 'any',
[ 'key' => null, 'value' => 'included spaces', 'operator' => 'contains', 'required' => true ],
[ 'key' => null, 'value' => 'world', 'operator' => 'contains' ],
[ 'key' => null, 'value' => 'another', 'operator' => 'contains', 'required' => true ],
[ 'key' => null, 'value' => 'hello', 'operator' => 'contains' ],
]
],
$this->widget->filter_entries( array(), null, $args, true )
);

$this->assertEquals( $search_criteria_split_exact, $this->widget->filter_entries( array(), null, $args, true ) );
// Combined search
$_GET = [ 'gv_search' => 'regular words +with -without' ];
$this->assertEquals(
[
'field_filters' => [
'mode' => 'any',
[ 'key' => null, 'value' => 'regular', 'operator' => 'contains'],
[ 'key' => null, 'value' => 'words', 'operator' => 'contains'],
[ 'key' => null, 'value' => 'with', 'operator' => 'contains', 'required' => true ],
[ 'key' => null, 'value' => 'without', 'operator' => 'not contains'],
]
],
$this->widget->filter_entries( array(), null, $args, true )
);

$_GET = array(
'gv_search' => '%20with%20%20spaces'
Expand Down Expand Up @@ -1408,6 +1452,36 @@ public function test_search_all_basic() {
$entries = $view->get_entries()->fetch()->all();
$this->assertCount( 2, $entries );

$_GET['gv_search'] = 'hello world';
$entries = $view->get_entries()->fetch()->all();
$this->assertCount( 3, $entries );

$_GET['gv_search'] = '"hello world"';
$entries = $view->get_entries()->fetch()->all();
$this->assertCount( 1, $entries );

$_GET['gv_search'] = 'hello -world';
$entries = $view->get_entries()->fetch()->all();
$this->assertCount( 1, $entries );

$_GET['gv_search'] = '+world';
$entries = $view->get_entries()->fetch()->all();
$this->assertCount( 2, $entries );
$this->assertSame(
[ 'world', 'hello world' ],
array_map(
static function ( $entry ) {
return $entry['16'];
},
$entries
)
);

$_GET['gv_search'] = '-hello +world';
$entries = $view->get_entries()->fetch()->all();
$this->assertCount( 1, $entries );
$this->assertSame( 'world', $entries[0]['16'] );

$_GET = array();
}

Expand Down