diff --git a/plugins/woocommerce/changelog/fix-50891 b/plugins/woocommerce/changelog/fix-50891 new file mode 100644 index 00000000000..33cc44e00b0 --- /dev/null +++ b/plugins/woocommerce/changelog/fix-50891 @@ -0,0 +1,4 @@ +Significance: patch +Type: enhancement + +Add filter for response of `wc_rest_should_load_namespace` function to allow loading namespaces. diff --git a/plugins/woocommerce/includes/wc-rest-functions.php b/plugins/woocommerce/includes/wc-rest-functions.php index 3eeec672a27..e9b3055cc9f 100644 --- a/plugins/woocommerce/includes/wc-rest-functions.php +++ b/plugins/woocommerce/includes/wc-rest-functions.php @@ -410,8 +410,6 @@ function wc_rest_should_load_namespace( string $ns, string $rest_route = '' ): b 'wc/private', ); - // We can consider allowing filtering this list in the future. - $known_namespace_request = false; foreach ( $known_namespaces as $known_namespace ) { if ( str_starts_with( $rest_route, $known_namespace ) ) { @@ -424,5 +422,15 @@ function wc_rest_should_load_namespace( string $ns, string $rest_route = '' ): b return true; } - return str_starts_with( $rest_route, $ns ); + /** + * Filters whether a namespace should be loaded. + * + * @param bool $should_load True if the namespace should be loaded, false otherwise. + * @param string $ns The namespace to check. + * @param string $rest_route The REST route being checked. + * @param array $known_namespaces Known namespaces that we know are safe to not load if the request is not for them. + * + * @since 9.4 + */ + return apply_filters( 'wc_rest_should_load_namespace', str_starts_with( $rest_route, $ns ), $ns, $rest_route, $known_namespaces ); } diff --git a/plugins/woocommerce/tests/php/includes/wc-rest-functions-test.php b/plugins/woocommerce/tests/php/includes/wc-rest-functions-test.php index d5938d7fbcb..41d2dd8dfc4 100644 --- a/plugins/woocommerce/tests/php/includes/wc-rest-functions-test.php +++ b/plugins/woocommerce/tests/php/includes/wc-rest-functions-test.php @@ -27,4 +27,22 @@ class WCRestFunctionsTest extends WC_Unit_Test_Case { $this->assertFalse( wc_rest_should_load_namespace( 'wc-analytics', 'wc/v2' ) ); $this->assertTrue( wc_rest_should_load_namespace( 'wc/v2', 'wc/v2' ) ); } + + /** + * @testDox Test wc_rest_should_load_namespace known works with preload. + */ + public function test_wc_rest_should_load_namespace_known_works_with_preload() { + $memo = rest_preload_api_request( array(), '/wc/store/v1/cart' ); + $this->assertArrayHasKey( '/wc/store/v1/cart', $memo ); + } + + /** + * @testDox Test wc_rest_should_load_namespace filter. + */ + public function test_wc_rest_should_load_namespace_filter() { + $this->assertFalse( wc_rest_should_load_namespace( 'wc/v1', 'wc/v2' ) ); + add_filter( 'wc_rest_should_load_namespace', '__return_true' ); + $this->assertTrue( wc_rest_should_load_namespace( 'wc/v1', 'wc/v2' ) ); + remove_filter( 'wc_rest_should_load_namespace', '__return_true' ); + } }