diff --git a/src/wp-includes/block-editor.php b/src/wp-includes/block-editor.php index aaa249cb7b..a861ba3006 100644 --- a/src/wp-includes/block-editor.php +++ b/src/wp-includes/block-editor.php @@ -468,6 +468,17 @@ function block_editor_rest_api_preload( array $preload_paths, $block_editor_cont */ $backup_global_post = ! empty( $post ) ? clone $post : $post; + foreach ( $preload_paths as &$path ) { + if ( is_string( $path ) && ! str_starts_with( $path, '/' ) ) { + $path = '/' . $path; + continue; + } + + if ( is_array( $path ) && is_string( $path[0] ) && ! str_starts_with( $path[0], '/' ) ) { + $path[0] = '/' . $path[0]; + } + } + $preload_data = array_reduce( $preload_paths, 'rest_preload_api_request', diff --git a/tests/phpunit/tests/blocks/editor.php b/tests/phpunit/tests/blocks/editor.php index b2f9eb88ee..786fa2b19f 100644 --- a/tests/phpunit/tests/blocks/editor.php +++ b/tests/phpunit/tests/blocks/editor.php @@ -493,4 +493,53 @@ class Tests_Blocks_Editor extends WP_UnitTestCase { $this->assertStringContainsString( '"\/wp\/v2\/blocks"', $after ); $this->assertStringContainsString( '"\/wp\/v2\/types"', $after ); } + + /** + * @ticket 54558 + * @dataProvider data_block_editor_rest_api_preload_adds_missing_leading_slash + * + * @covers ::block_editor_rest_api_preload + * + * @param array $preload_paths The paths to preload. + * @param string $expected The expected substring. + */ + public function test_block_editor_rest_api_preload_adds_missing_leading_slash( array $preload_paths, $expected ) { + block_editor_rest_api_preload( $preload_paths, new WP_Block_Editor_Context() ); + $haystack = implode( '', wp_scripts()->registered['wp-api-fetch']->extra['after'] ); + $this->assertStringContainsString( $expected, $haystack ); + } + + /** + * Data provider. + * + * @return array + */ + public function data_block_editor_rest_api_preload_adds_missing_leading_slash() { + return array( + 'a string without a slash' => array( + 'preload_paths' => array( 'wp/v2/blocks' ), + 'expected' => '\/wp\/v2\/blocks', + ), + 'a string with a slash' => array( + 'preload_paths' => array( '/wp/v2/blocks' ), + 'expected' => '\/wp\/v2\/blocks', + ), + 'a string starting with a question mark' => array( + 'preload_paths' => array( '?context=edit' ), + 'expected' => '/?context=edit', + ), + 'an array with a string without a slash' => array( + 'preload_paths' => array( array( 'wp/v2/blocks', 'OPTIONS' ) ), + 'expected' => '\/wp\/v2\/blocks', + ), + 'an array with a string with a slash' => array( + 'preload_paths' => array( array( '/wp/v2/blocks', 'OPTIONS' ) ), + 'expected' => '\/wp\/v2\/blocks', + ), + 'an array with a string starting with a question mark' => array( + 'preload_paths' => array( array( '?context=edit', 'OPTIONS' ) ), + 'expected' => '\/?context=edit', + ), + ); + } }