Add filter to overwrite response of `wc_rest_should_load_namespace` (#50902)

* Add filter to allow overwriting `wc_rest_should_load_namespace`.

* Unit tests + changelog.

* Add doc block.

* Update version number.

Co-authored-by: Corey McKrill <916023+coreymckrill@users.noreply.github.com>

---------

Co-authored-by: Corey McKrill <916023+coreymckrill@users.noreply.github.com>
This commit is contained in:
Vedanshu Jain 2024-08-30 16:42:28 +05:30 committed by GitHub
parent 40cde50879
commit 5999ea6716
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 33 additions and 3 deletions

View File

@ -0,0 +1,4 @@
Significance: patch
Type: enhancement
Add filter for response of `wc_rest_should_load_namespace` function to allow loading namespaces.

View File

@ -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 );
}

View File

@ -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' );
}
}