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

Allow truthy values for enabling weighting #2673

Merged
merged 1 commit into from
Mar 28, 2022
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
14 changes: 8 additions & 6 deletions includes/classes/Feature/Search/Weighting.php
Original file line number Diff line number Diff line change
Expand Up @@ -546,15 +546,17 @@ public function post_type_has_fields( $post_type, $args = [] ) {
$weights = $weight_config[ $post_type ];
}

$weights = array_diff_key( $weights, $ignore_keys );
$fields = array_diff_key( $weights, $ignore_keys );

$found_enabled = array_search( true, array_column( $weights, 'enabled' ), true );

if ( false !== $found_enabled ) {
return true;
$found_enabled = false;
foreach ( $fields as $field ) {
if ( filter_var( $field['enabled'], FILTER_VALIDATE_BOOLEAN ) ) {
$found_enabled = true;
break;
}
}

return false;
return $found_enabled;
}

/**
Expand Down
39 changes: 39 additions & 0 deletions tests/php/features/TestWeighting.php
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,45 @@ public function testPostTypeHasFieldsWithCustomConfig() {
$this->assertFalse( $this->get_weighting_feature()->post_type_has_fields( 'page' ) );
}

/**
* Check if `post_type_has_fields()` behaves correctly when using the `ep_weighting_configuration_for_search` filter.
*
* @since 4.1.0
*/
public function testPostTypeHasFieldsWithCustomConfigViaFilter() {
$function = function() {
return [
'page' => [],
'post' => [
'post_title' => [
'enabled' => 'on',
'weight' => 1
]
],
'test' => [
'post_title' => [
'enabled' => true,
'weight' => 1
]
],
'test-2' => [
'post_title' => [
'enabled' => 10, // This is not considered a "truthy" value
'weight' => 1
]
],
];
};
add_filter( 'ep_weighting_configuration_for_search', $function );

$this->assertTrue( $this->get_weighting_feature()->post_type_has_fields( 'post' ) );
$this->assertFalse( $this->get_weighting_feature()->post_type_has_fields( 'page' ) );
$this->assertTrue( $this->get_weighting_feature()->post_type_has_fields( 'test' ) );
$this->assertFalse( $this->get_weighting_feature()->post_type_has_fields( 'test-2' ) );

remove_filter( 'ep_weighting_configuration_for_search', $function );
}

public function testDoWeightingWithQueryContainsSearchFields() {
// Test search fields are set on the query.
$this->assertSame( ['do', 'nothing'], $this->get_weighting_feature()->do_weighting( ['do', 'nothing'], ['search_fields' => [ 'post_title' ] ] ) );
Expand Down