From 2ebb3e1009996b6cbcdea32d67f3be4bb24a0d14 Mon Sep 17 00:00:00 2001 From: Felipe Elia Date: Tue, 22 Mar 2022 10:33:23 -0300 Subject: [PATCH] Weighting: truthy values for 'enabled' --- includes/classes/Feature/Search/Weighting.php | 14 ++++--- tests/php/features/TestWeighting.php | 39 +++++++++++++++++++ 2 files changed, 47 insertions(+), 6 deletions(-) diff --git a/includes/classes/Feature/Search/Weighting.php b/includes/classes/Feature/Search/Weighting.php index 95902a8ea4..0d24ec9291 100644 --- a/includes/classes/Feature/Search/Weighting.php +++ b/includes/classes/Feature/Search/Weighting.php @@ -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; } /** diff --git a/tests/php/features/TestWeighting.php b/tests/php/features/TestWeighting.php index 295b5e38ff..3defa972f9 100644 --- a/tests/php/features/TestWeighting.php +++ b/tests/php/features/TestWeighting.php @@ -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' ] ] ) );