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

Update REST API to handle slug refs #44975

Open
wants to merge 3 commits into
base: try/nav-block-use-slugs-for-ref
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?php
/**
* REST API: Gutenberg_REST_Templates_Controller class
*
* @package Gutenberg
* @subpackage REST_API
*/

/**
* Base Templates REST API Controller.
*/
class Gutenberg_REST_Navigation_Controller extends WP_REST_Posts_Controller {

/**
* Registers the controllers routes.
*
* @return void
*/
public function register_routes() {

parent::register_routes();

// Lists a single nav item based on the given id or slug.
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/((?P<id>[\d]+)|(?P<slug>[\w\-]+))',
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both id and slug are needed in this request otherwise backwards compatibility is broken.

array(
'args' => array(
'slug' => array(
'description' => __( 'The slug identifier for a Navigation', 'gutenberg' ),
'type' => 'string',
),
),
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => array( $this, 'get_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::READABLE ),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'update_item' ),
'permission_callback' => array( $this, 'update_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
),
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => array( $this, 'delete_item' ),
'permission_callback' => array( $this, 'delete_item_permissions_check' ),
'args' => array(
'force' => array(
'type' => 'boolean',
'default' => false,
'description' => __( 'Whether to bypass Trash and force deletion.' ),
),
),
),
'allow_batch' => $this->allow_batch,
'schema' => array( $this, 'get_public_item_schema' ),
)
);
}

/**
* Overide WP_REST_Posts_Controller parent function to query for
* `wp_navigation` posts by slug (post_name) instead of ID.
*
* This is required to successfully process OPTIONS requests as with
* these the `rest_request_before_callbacks` method which is used to
* map slug to postId does not run which means `get_post` will not
* behave as expected.
*
* The function will continue to delegate to the parent implementation
* if the $id argument is ID-based, thereby ensuring backwards
* compatbility.
*
* It may be possible to remove this implemenation in future releases.
*
* See: https://github.com/WordPress/gutenberg/pull/43703.
*
* @param string $id the slug of the Navigation post.
* @return WP_Post|null
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrong return type.

*/
protected function get_post( $id ) {

// Handle ID based $id param.
if ( is_numeric( $id ) ) {
return parent::get_post( $id );
}

// For string based $id the argument is a "slug".
// Lookup Post using `post_name` query.
$slug = $id;

$args = array(
'name' => $slug,
'post_type' => 'wp_navigation',
'nopaging' => true,
'posts_per_page' => '1',
'update_post_term_cache' => false,
'no_found_rows' => true,
);

// Query for the Navigation Post by slug (post_name).
$query = new WP_Query( $args );

if ( empty( $query->posts ) ) {
return new WP_Error(
'rest_post_not_found',
__( 'No navigation found.' ),
array( 'status' => 404 )
);
}

return $query->posts[0];
}
}
112 changes: 112 additions & 0 deletions lib/compat/wordpress-6.2/rest-api.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php
/**
* Overrides Core's wp-includes/rest-api.php and registers the new endpoint for WP 6.2.
*
* @package gutenberg
*/

/**
* Use custom REST API Controller for Navigation Posts
*
* @param array $args the post type arguments.
* @param string $post_type Post type key.
* @return array the filtered post type arguments with the new REST Controller set.
*/
function gutenberg_update_navigation_rest_controller( $args, $post_type ) {
if ( in_array( $post_type, array( 'wp_navigation' ), true ) ) {
// Original set in
// https://github.com/WordPress/wordpress-develop/blob/6cbed78c94b9d8c6a9b4c8b472b88ee0cd56528c/src/wp-includes/post.php#L528.
$args['rest_controller_class'] = 'Gutenberg_REST_Navigation_Controller';
}
return $args;
}
add_filter( 'register_post_type_args', 'gutenberg_update_navigation_rest_controller', 10, 2 );

/**
* Sets the 'ID' field of the WP_REST_Request to be the Post retrieved by `slug` if
* one is present in the request URL.
*
* Allows Navigation Posts to be requested by slug by looking up the Post
* by slug and using the resulting postID of the record to set the 'ID' field of the
* request before it is handled.
*
* This ensures that the same handler logic can be reused whether the endpoint
* is dealing with slugs or IDs.
*
* @param WP_REST_Response|WP_HTTP_Response|WP_Error $response Result to send to the client.
* @param array $handler Route handler used for the request.
* @param WP_REST_Request $request Request used to generate the response.
* @return WP_REST_Response the response.
*/
function gutenberg_transform_slug_to_post_id( $response, $handler, WP_REST_Request $request ) {

$route = rest_get_route_for_post_type_items( 'wp_navigation' );

// Ignore non-Navigation REST API requests.
if ( ! str_starts_with( $request->get_route(), $route ) ) {
return $response;
}

// Get the slug from the request **URL** (not the request body).
// PUT requests will have a param of `slug` in both the URL and (potentially)
// in the body. In all cases only the slug in the URL should be mapped to a
// postId in order that the correct post to be updated can be retrived.
// The `slug` within the body should be preserved "as is".
$slug = isset( $request->get_url_params()['slug'] ) ? $request->get_url_params()['slug'] : null;

// If no slug provided assume ID and exit early.
if ( empty( $slug ) ) {
return $response;
}

$args = array(
'name' => $slug, // query by slug
'post_type' => 'wp_navigation',
'nopaging' => true,
'posts_per_page' => '1',
'update_post_term_cache' => false,
'no_found_rows' => true,
);

// Query for the Navigation Post by slug (post_name).
$query = new WP_Query( $args );

if ( empty( $query->posts ) ) {
return new WP_Error(
'rest_post_not_found',
__( 'No navigation found.' ),
array( 'status' => 404 )
);
}

// Set the post ID of the request based on the slug.
$request['id'] = $query->posts[0]->ID;

return $response;
}
add_filter( 'rest_request_before_callbacks', 'gutenberg_transform_slug_to_post_id', 10, 3 );

/**
* Updates the REST route for Navigation posts to use the post slug
* instead of the postId.
*
* @param string $route the route path.
* @param WP_Post $post the post object.
* @return string the updated route.
*/
function gutenberg_update_navigation_rest_route_for_post( $route, WP_Post $post ) {

if ( $post->post_type !== 'wp_navigation' ) {
return $route;
}

$post_type_route = rest_get_route_for_post_type_items( $post->post_type );

if ( ! $post_type_route ) {
return '';
}

// Replace Post ID in route with Post "Slug" (post_name).
return sprintf( '%s/%s', $post_type_route, $post->post_name );
}
add_filter( 'rest_route_for_post', 'gutenberg_update_navigation_rest_route_for_post', 10, 2 );
4 changes: 4 additions & 0 deletions lib/load.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ function gutenberg_is_experiment_enabled( $name ) {
require_once __DIR__ . '/compat/wordpress-6.1/class-gutenberg-rest-templates-controller.php';
require_once __DIR__ . '/compat/wordpress-6.1/rest-api.php';

// WordPress 6.2 compat.
require_once __DIR__ . '/compat/wordpress-6.2/class-gutenberg-rest-navigation-controller.php';
require_once __DIR__ . '/compat/wordpress-6.2/rest-api.php';

// Experimental.
if ( ! class_exists( 'WP_Rest_Customizer_Nonces' ) ) {
require_once __DIR__ . '/experimental/class-wp-rest-customizer-nonces.php';
Expand Down
Loading