diff --git a/lib/class-wp-rest-menu-items-controller.php b/lib/class-wp-rest-menu-items-controller.php new file mode 100644 index 00000000000000..18079b23ed711e --- /dev/null +++ b/lib/class-wp-rest-menu-items-controller.php @@ -0,0 +1,1062 @@ +namespace = '__experimental'; + } + + /** + * Get the post, if the ID is valid. + * + * @param int $id Supplied ID. + * + * @return object|WP_Error Post object if ID is valid, WP_Error otherwise. + */ + protected function get_post( $id ) { + return $this->get_nav_menu_item( $id ); + } + + /** + * Get the nav menu item, if the ID is valid. + * + * @param int $id Supplied ID. + * + * @return object|WP_Error Post object if ID is valid, WP_Error otherwise. + */ + protected function get_nav_menu_item( $id ) { + $post = parent::get_post( $id ); + if ( is_wp_error( $post ) ) { + return $post; + } + $nav_item = wp_setup_nav_menu_item( $post ); + + return $nav_item; + } + + /** + * Checks if a given request has access to read a menu item if they have access to edit them. + * + * @param WP_REST_Request $request Full details about the request. + * @return bool|WP_Error True if the request has read access for the item, WP_Error object otherwise. + */ + public function get_item_permissions_check( $request ) { + $post = $this->get_post( $request['id'] ); + if ( is_wp_error( $post ) ) { + return $post; + } + if ( $post && ! $this->check_update_permission( $post ) ) { + return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot view this menu item, unless you have access to permission edit it. ', 'gutenberg' ), array( 'status' => rest_authorization_required_code() ) ); + } + + return parent::get_item_permissions_check( $request ); + } + + /** + * Checks if a given request has access to read menu items if they have access to edit them. + * + * @param WP_REST_Request $request Full details about the request. + * @return true|WP_Error True if the request has read access, WP_Error object otherwise. + */ + public function get_items_permissions_check( $request ) { + $post_type = get_post_type_object( $this->post_type ); + if ( ! current_user_can( $post_type->cap->edit_posts ) ) { + if ( 'edit' === $request['context'] ) { + return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit posts in this post type.', 'gutenberg' ), array( 'status' => rest_authorization_required_code() ) ); + } + return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot view these menu items, unless you have access to permission edit them. ', 'gutenberg' ), array( 'status' => rest_authorization_required_code() ) ); + } + return true; + } + + /** + * Creates a single post. + * + * @param WP_REST_Request $request Full details about the request. + * + * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. + */ + public function create_item( $request ) { + if ( ! empty( $request['id'] ) ) { + return new WP_Error( 'rest_post_exists', __( 'Cannot create existing post.', 'gutenberg' ), array( 'status' => 400 ) ); + } + + $prepared_nav_item = $this->prepare_item_for_database( $request ); + + if ( is_wp_error( $prepared_nav_item ) ) { + return $prepared_nav_item; + } + $prepared_nav_item = (array) $prepared_nav_item; + + $nav_menu_item_id = wp_update_nav_menu_item( $prepared_nav_item['menu-id'], $prepared_nav_item['menu-item-db-id'], $prepared_nav_item ); + if ( is_wp_error( $nav_menu_item_id ) ) { + if ( 'db_insert_error' === $nav_menu_item_id->get_error_code() ) { + $nav_menu_item_id->add_data( array( 'status' => 500 ) ); + } else { + $nav_menu_item_id->add_data( array( 'status' => 400 ) ); + } + + return $nav_menu_item_id; + } + + $nav_menu_item = $this->get_nav_menu_item( $nav_menu_item_id ); + if ( is_wp_error( $nav_menu_item ) ) { + $nav_menu_item->add_data( array( 'status' => 404 ) ); + + return $nav_menu_item; + } + + /** + * Fires after a single nav menu item is created or updated via the REST API. + * + * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. + * + * @param object $nav_menu_item Inserted or updated nav item object. + * @param WP_REST_Request $request Request object. + * @param bool $creating True when creating a post, false when updating. + * SA + */ + do_action( "rest_insert_{$this->post_type}", $nav_menu_item, $request, true ); + + $schema = $this->get_item_schema(); + + if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { + $meta_update = $this->meta->update_value( $request['meta'], $nav_menu_item_id ); + + if ( is_wp_error( $meta_update ) ) { + return $meta_update; + } + } + + $nav_menu_item = $this->get_nav_menu_item( $nav_menu_item_id ); + $fields_update = $this->update_additional_fields_for_object( $nav_menu_item, $request ); + + if ( is_wp_error( $fields_update ) ) { + return $fields_update; + } + + $request->set_param( 'context', 'edit' ); + + /** + * Fires after a single nav menu item is completely created or updated via the REST API. + * + * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. + * + * @param object $nav_menu_item Inserted or updated nav item object. + * @param WP_REST_Request $request Request object. + * @param bool $creating True when creating a post, false when updating. + */ + do_action( "rest_after_insert_{$this->post_type}", $nav_menu_item, $request, true ); + + $response = $this->prepare_item_for_response( $nav_menu_item, $request ); + $response = rest_ensure_response( $response ); + + $response->set_status( 201 ); + $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $nav_menu_item_id ) ) ); + + return $response; + } + + /** + * Updates a single nav menu item. + * + * @param WP_REST_Request $request Full details about the request. + * + * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. + */ + public function update_item( $request ) { + $valid_check = $this->get_nav_menu_item( $request['id'] ); + if ( is_wp_error( $valid_check ) ) { + return $valid_check; + } + + $prepared_nav_item = $this->prepare_item_for_database( $request ); + + if ( is_wp_error( $prepared_nav_item ) ) { + return $prepared_nav_item; + } + + $prepared_nav_item = (array) $prepared_nav_item; + + $nav_menu_item_id = wp_update_nav_menu_item( $prepared_nav_item['menu-id'], $prepared_nav_item['menu-item-db-id'], $prepared_nav_item ); + + if ( is_wp_error( $nav_menu_item_id ) ) { + if ( 'db_update_error' === $nav_menu_item_id->get_error_code() ) { + $nav_menu_item_id->add_data( array( 'status' => 500 ) ); + } else { + $nav_menu_item_id->add_data( array( 'status' => 400 ) ); + } + + return $nav_menu_item_id; + } + + $nav_menu_item = $this->get_nav_menu_item( $nav_menu_item_id ); + if ( is_wp_error( $nav_menu_item ) ) { + $nav_menu_item->add_data( array( 'status' => 404 ) ); + + return $nav_menu_item; + } + + /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */ + do_action( "rest_insert_{$this->post_type}", $nav_menu_item, $request, false ); + + $schema = $this->get_item_schema(); + + if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { + $meta_update = $this->meta->update_value( $request['meta'], $nav_menu_item->ID ); + + if ( is_wp_error( $meta_update ) ) { + return $meta_update; + } + } + + $nav_menu_item = $this->get_nav_menu_item( $nav_menu_item_id ); + $fields_update = $this->update_additional_fields_for_object( $nav_menu_item, $request ); + + if ( is_wp_error( $fields_update ) ) { + return $fields_update; + } + + $request->set_param( 'context', 'edit' ); + + /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php */ + do_action( "rest_after_insert_{$this->post_type}", $nav_menu_item, $request, false ); + + $response = $this->prepare_item_for_response( $nav_menu_item, $request ); + + return rest_ensure_response( $response ); + } + + /** + * Deletes a single menu item. + * + * @param WP_REST_Request $request Full details about the request. + * @return true|WP_Error True on success, or WP_Error object on failure. + */ + public function delete_item( $request ) { + $menu_item = $this->get_nav_menu_item( $request['id'] ); + if ( is_wp_error( $menu_item ) ) { + return $menu_item; + } + + $force = isset( $request['force'] ) ? (bool) $request['force'] : false; + + // We don't support trashing for menu items. + if ( ! $force ) { + /* translators: %s: force=true */ + return new WP_Error( 'rest_trash_not_supported', sprintf( __( "Menu items do not support trashing. Set '%s' to delete.", 'gutenberg' ), 'force=true' ), array( 'status' => 501 ) ); + } + + $previous = $this->prepare_item_for_response( $menu_item, $request ); + + $result = wp_delete_post( $request['id'], true ); + + if ( ! $result ) { + return new WP_Error( 'rest_cannot_delete', __( 'The post cannot be deleted.', 'gutenberg' ), array( 'status' => 500 ) ); + } + + $response = new WP_REST_Response(); + $response->set_data( + array( + 'deleted' => true, + 'previous' => $previous->get_data(), + ) + ); + + /** + * Fires immediately after a single menu item is deleted or trashed via the REST API. + * + * They dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. + * + * @param Object $menu_item The deleted or trashed menu item. + * @param WP_REST_Response $response The response data. + * @param WP_REST_Request $request The request sent to the API. + */ + do_action( "rest_delete_{$this->post_type}", $menu_item, $response, $request ); + + return $response; + } + + /** + * Prepares a single post for create or update. + * + * @param WP_REST_Request $request Request object. + * + * @return stdClass|WP_Error + */ + protected function prepare_item_for_database( $request ) { + $menu_item_db_id = $request['id']; + $menu_item_obj = $this->get_nav_menu_item( $menu_item_db_id ); + // Need to persist the menu item data. See https://core.trac.wordpress.org/ticket/28138 . + if ( ! is_wp_error( $menu_item_obj ) ) { + // Correct the menu position if this was the first item. See https://core.trac.wordpress.org/ticket/28140 . + $position = ( 0 === $menu_item_obj->menu_order ) ? 1 : $menu_item_obj->menu_order; + + $prepared_nav_item = array( + 'menu-item-db-id' => $menu_item_db_id, + 'menu-item-object-id' => $menu_item_obj->object_id, + 'menu-item-object' => $menu_item_obj->object, + 'menu-item-parent-id' => $menu_item_obj->menu_item_parent, + 'menu-item-position' => $position, + 'menu-item-title' => $menu_item_obj->title, + 'menu-item-url' => $menu_item_obj->url, + 'menu-item-description' => $menu_item_obj->description, + 'menu-item-attr-title' => $menu_item_obj->attr_title, + 'menu-item-target' => $menu_item_obj->target, + // Stored in the database as a string. + 'menu-item-classes' => implode( ' ', $menu_item_obj->classes ), + 'menu-item-xfn' => $menu_item_obj->xfn, + 'menu-item-status' => $menu_item_obj->post_status, + 'menu-id' => $this->get_menu_id( $menu_item_db_id ), + ); + } else { + $prepared_nav_item = array( + 'menu-id' => 0, + 'menu-item-db-id' => 0, + 'menu-item-object-id' => 0, + 'menu-item-object' => '', + 'menu-item-parent-id' => 0, + 'menu-item-position' => 0, + 'menu-item-type' => 'custom', + 'menu-item-title' => '', + 'menu-item-url' => '', + 'menu-item-description' => '', + 'menu-item-attr-title' => '', + 'menu-item-target' => '', + 'menu-item-classes' => '', + 'menu-item-xfn' => '', + 'menu-item-status' => 'publish', + ); + } + + $mapping = array( + 'menu-item-db-id' => 'id', + 'menu-item-object-id' => 'object_id', + 'menu-item-object' => 'object', + 'menu-item-parent-id' => 'parent', + 'menu-item-position' => 'menu_order', + 'menu-item-type' => 'type', + 'menu-item-url' => 'url', + 'menu-item-description' => 'description', + 'menu-item-attr-title' => 'attr_title', + 'menu-item-target' => 'target', + 'menu-item-classes' => 'classes', + 'menu-item-xfn' => 'xfn', + 'menu-item-status' => 'status', + ); + + $schema = $this->get_item_schema(); + + foreach ( $mapping as $original => $api_request ) { + if ( ! empty( $schema['properties'][ $api_request ] ) && isset( $request[ $api_request ] ) ) { + $check = rest_validate_value_from_schema( $request[ $api_request ], $schema['properties'][ $api_request ] ); + if ( is_wp_error( $check ) ) { + $check->add_data( array( 'status' => 400 ) ); + return $check; + } + $prepared_nav_item[ $original ] = rest_sanitize_value_from_schema( $request[ $api_request ], $schema['properties'][ $api_request ] ); + } + } + + $taxonomy = get_taxonomy( 'nav_menu' ); + $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; + // If menus submitted, cast to int. + if ( isset( $request[ $base ] ) && ! empty( $request[ $base ] ) ) { + $prepared_nav_item['menu-id'] = absint( $request[ $base ] ); + } + + // Nav menu title. + if ( ! empty( $schema['properties']['title'] ) && isset( $request['title'] ) ) { + if ( is_string( $request['title'] ) ) { + $prepared_nav_item['menu-item-title'] = $request['title']; + } elseif ( ! empty( $request['title']['raw'] ) ) { + $prepared_nav_item['menu-item-title'] = $request['title']['raw']; + } + } + + // Check if object id exists before saving. + if ( ! $prepared_nav_item['menu-item-object'] ) { + // If taxonony, check if term exists. + if ( 'taxonomy' === $prepared_nav_item['menu-item-type'] ) { + $original = get_term( absint( $prepared_nav_item['menu-item-object-id'] ) ); + if ( empty( $original ) || is_wp_error( $original ) ) { + return new WP_Error( 'rest_term_invalid_id', __( 'Invalid term ID.', 'gutenberg' ), array( 'status' => 400 ) ); + } + $prepared_nav_item['menu-item-object'] = get_term_field( 'taxonomy', $original ); + + // If post, check if post object exists. + } elseif ( 'post_type' === $prepared_nav_item['menu-item-type'] ) { + $original = get_post( absint( $prepared_nav_item['menu-item-object-id'] ) ); + if ( empty( $original ) ) { + return new WP_Error( 'rest_post_invalid_id', __( 'Invalid post ID.', 'gutenberg' ), array( 'status' => 400 ) ); + } + $prepared_nav_item['menu-item-object'] = get_post_type( $original ); + } + } + + // If post type archive, check if post type exists. + if ( 'post_type_archive' === $prepared_nav_item['menu-item-type'] ) { + $post_type = ( $prepared_nav_item['menu-item-object'] ) ? $prepared_nav_item['menu-item-object'] : false; + $original = get_post_type_object( $post_type ); + if ( empty( $original ) ) { + return new WP_Error( 'rest_post_invalid_type', __( 'Invalid post type.', 'gutenberg' ), array( 'status' => 400 ) ); + } + } + + // Check if menu item is type custom, then title and url are required. + if ( 'custom' === $prepared_nav_item['menu-item-type'] ) { + if ( '' === $prepared_nav_item['menu-item-title'] ) { + return new WP_Error( 'rest_title_required', __( 'Title require if menu item of type custom.', 'gutenberg' ), array( 'status' => 400 ) ); + } + if ( empty( $prepared_nav_item['menu-item-url'] ) ) { + return new WP_Error( 'rest_url_required', __( 'URL require if menu item of type custom.', 'gutenberg' ), array( 'status' => 400 ) ); + } + } + + // If menu id is set, valid the value of menu item position and parent id. + if ( ! empty( $prepared_nav_item['menu-id'] ) ) { + // Check if nav menu is valid. + if ( ! is_nav_menu( $prepared_nav_item['menu-id'] ) ) { + return new WP_Error( 'invalid_menu_id', __( 'Invalid menu ID.', 'gutenberg' ), array( 'status' => 400 ) ); + } + + // If menu item position is set to 0, insert as the last item in the existing menu. + $menu_items = wp_get_nav_menu_items( $prepared_nav_item['menu-id'], array( 'post_status' => 'publish,draft' ) ); + if ( 0 === (int) $prepared_nav_item['menu-item-position'] ) { + if ( $menu_items ) { + $last_item = array_pop( $menu_items ); + if ( $last_item && isset( $last_item->menu_order ) ) { + $prepared_nav_item['menu-item-position'] = $last_item->menu_order + 1; + } else { + $prepared_nav_item['menu-item-position'] = count( $menu_items ); + } + } else { + $prepared_nav_item['menu-item-position'] = 1; + } + } + + // Check if existing menu position is already in use by another menu item. + $menu_item_ids = array(); + foreach ( $menu_items as $menu_item ) { + $menu_item_ids[] = $menu_item->ID; + if ( $menu_item->ID !== (int) $menu_item_db_id ) { + if ( (int) $prepared_nav_item['menu-item-position'] === (int) $menu_item->menu_order ) { + return new WP_Error( 'invalid_menu_order', __( 'Invalid menu position.', 'gutenberg' ), array( 'status' => 400 ) ); + } + } + } + + // Check if valid parent id is valid nav menu item in menu. + if ( $prepared_nav_item['menu-item-parent-id'] ) { + if ( ! is_nav_menu_item( $prepared_nav_item['menu-item-parent-id'] ) ) { + return new WP_Error( 'invalid_menu_item_parent', __( 'Invalid menu item parent.', 'gutenberg' ), array( 'status' => 400 ) ); + } + if ( ! $menu_item_ids || ! in_array( $prepared_nav_item['menu-item-parent-id'], $menu_item_ids, true ) ) { + return new WP_Error( 'invalid_item_parent', __( 'Invalid menu item parent.', 'gutenberg' ), array( 'status' => 400 ) ); + } + } + } + + foreach ( array( 'menu-item-object-id', 'menu-item-parent-id' ) as $key ) { + // Note we need to allow negative-integer IDs for previewed objects not inserted yet. + $prepared_nav_item[ $key ] = intval( $prepared_nav_item[ $key ] ); + } + + foreach ( array( 'menu-item-type', 'menu-item-object', 'menu-item-target' ) as $key ) { + $prepared_nav_item[ $key ] = sanitize_key( $prepared_nav_item[ $key ] ); + } + + // Valid xfn and classes are an array. + foreach ( array( 'menu-item-xfn', 'menu-item-classes' ) as $key ) { + $value = $prepared_nav_item[ $key ]; + if ( ! is_array( $value ) ) { + $value = wp_parse_list( $value ); + } + $prepared_nav_item[ $key ] = implode( ' ', array_map( 'sanitize_html_class', $value ) ); + } + + // Apply the same filters as when calling wp_insert_post(). + + /** This filter is documented in wp-includes/post.php */ + $prepared_nav_item['menu-item-title'] = wp_unslash( apply_filters( 'title_save_pre', wp_slash( $prepared_nav_item['menu-item-title'] ) ) ); + + /** This filter is documented in wp-includes/post.php */ + $prepared_nav_item['menu-item-attr-title'] = wp_unslash( apply_filters( 'excerpt_save_pre', wp_slash( $prepared_nav_item['menu-item-attr-title'] ) ) ); + + /** This filter is documented in wp-includes/post.php */ + $prepared_nav_item['menu-item-description'] = wp_unslash( apply_filters( 'content_save_pre', wp_slash( $prepared_nav_item['menu-item-description'] ) ) ); + + // Valid url. + if ( '' !== $prepared_nav_item['menu-item-url'] ) { + $prepared_nav_item['menu-item-url'] = esc_url_raw( $prepared_nav_item['menu-item-url'] ); + if ( '' === $prepared_nav_item['menu-item-url'] ) { + // Fail sanitization if URL is invalid. + return new WP_Error( 'invalid_url', __( 'Invalid URL.', 'gutenberg' ), array( 'status' => 400 ) ); + } + } + // Only draft / publish are valid post status for menu items. + if ( 'publish' !== $prepared_nav_item['menu-item-status'] ) { + $prepared_nav_item['menu-item-status'] = 'draft'; + } + + $prepared_nav_item = (object) $prepared_nav_item; + + /** + * Filters a post before it is inserted via the REST API. + * + * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. + * + * @param stdClass $prepared_post An object representing a single post prepared + * for inserting or updating the database. + * @param WP_REST_Request $request Request object. + */ + return apply_filters( "rest_pre_insert_{$this->post_type}", $prepared_nav_item, $request ); + } + + /** + * Prepares a single post output for response. + * + * @param object $post Post object. + * @param WP_REST_Request $request Request object. + * + * @return WP_REST_Response Response object. + */ + public function prepare_item_for_response( $post, $request ) { + $fields = $this->get_fields_for_response( $request ); + + // Base fields for every post. + $menu_item = wp_setup_nav_menu_item( $post ); + $data = array(); + if ( in_array( 'id', $fields, true ) ) { + $data['id'] = $menu_item->ID; + } + + if ( in_array( 'title', $fields, true ) ) { + add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) ); + + $data['title'] = array( + 'raw' => $menu_item->post_title, + 'rendered' => $menu_item->title, + ); + + remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) ); + } + + if ( in_array( 'status', $fields, true ) ) { + $data['status'] = $menu_item->post_status; + } + + if ( in_array( 'url', $fields, true ) ) { + $data['url'] = $menu_item->url; + } + + if ( in_array( 'attr_title', $fields, true ) ) { + // Same as post_excerpt. + $data['attr_title'] = $menu_item->attr_title; + } + + if ( in_array( 'description', $fields, true ) ) { + // Same as post_content. + $data['description'] = $menu_item->description; + } + + if ( in_array( 'type', $fields, true ) ) { + // Using 'item_type' since 'type' already exists. + $data['type'] = $menu_item->type; + } + + if ( in_array( 'type_label', $fields, true ) ) { + // Using 'item_type_label' to match up with 'item_type' - IS READ ONLY! + $data['type_label'] = $menu_item->type_label; + } + + if ( in_array( 'object', $fields, true ) ) { + $data['object'] = $menu_item->object; + } + + if ( in_array( 'object_id', $fields, true ) ) { + // Usually is a string, but lets expose as an integer. + $data['object_id'] = absint( $menu_item->object_id ); + } + + if ( in_array( 'parent', $fields, true ) ) { + // Same as post_parent, expose as integer. + $data['parent'] = absint( $menu_item->menu_item_parent ); + } + + if ( in_array( 'menu_order', $fields, true ) ) { + // Same as post_parent, expose as integer. + $data['menu_order'] = absint( $menu_item->menu_order ); + } + + if ( in_array( 'menu_id', $fields, true ) ) { + $data['menu_id'] = $this->get_menu_id( $menu_item->ID ); + } + + if ( in_array( 'target', $fields, true ) ) { + $data['target'] = $menu_item->target; + } + + if ( in_array( 'classes', $fields, true ) ) { + $data['classes'] = (array) $menu_item->classes; + } + + if ( in_array( 'xfn', $fields, true ) ) { + $data['xfn'] = array_map( 'sanitize_html_class', explode( ' ', $menu_item->xfn ) ); + } + + if ( in_array( 'meta', $fields, true ) ) { + $data['meta'] = $this->meta->get_value( $menu_item->ID, $request ); + } + + $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); + + foreach ( $taxonomies as $taxonomy ) { + $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; + + if ( in_array( $base, $fields, true ) ) { + $terms = get_the_terms( $post, $taxonomy->name ); + $data[ $base ] = $terms ? array_values( wp_list_pluck( $terms, 'term_id' ) ) : array(); + } + } + + $context = ! empty( $request['context'] ) ? $request['context'] : 'view'; + $data = $this->add_additional_fields_to_object( $data, $request ); + $data = $this->filter_response_by_context( $data, $context ); + + // Wrap the data in a response object. + $response = rest_ensure_response( $data ); + + $links = $this->prepare_links( $menu_item ); + $response->add_links( $links ); + + if ( ! empty( $links['self']['href'] ) ) { + $actions = $this->get_available_actions( $menu_item, $request ); + + $self = $links['self']['href']; + + foreach ( $actions as $rel ) { + $response->add_link( $rel, $self ); + } + } + + /** + * Filters the post data for a response. + * + * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug. + * + * @param WP_REST_Response $response The response object. + * @param object $post Post object. + * @param WP_REST_Request $request Request object. + */ + return apply_filters( "rest_prepare_{$this->post_type}", $response, $post, $request ); + } + + /** + * Prepares links for the request. + * + * @param object $menu_item Menu object. + * + * @return array Links for the given post. + */ + protected function prepare_links( $menu_item ) { + $links = parent::prepare_links( $menu_item ); + + if ( 'post_type' === $menu_item->type && ! empty( $menu_item->object_id ) ) { + $post_type_object = get_post_type_object( $menu_item->object ); + if ( $post_type_object->show_in_rest ) { + $rest_base = ! empty( $post_type_object->rest_base ) ? $post_type_object->rest_base : $post_type_object->name; + $url = rest_url( sprintf( 'wp/v2/%s/%d', $rest_base, $menu_item->object_id ) ); + $links['https://api.w.org/object'][] = array( + 'href' => $url, + 'post_type' => $menu_item->type, + 'embeddable' => true, + ); + } + } elseif ( 'taxonomy' === $menu_item->type && ! empty( $menu_item->object_id ) ) { + $taxonomy_object = get_taxonomy( $menu_item->object ); + if ( $taxonomy_object->show_in_rest ) { + $rest_base = ! empty( $taxonomy_object->rest_base ) ? $taxonomy_object->rest_base : $taxonomy_object->name; + $url = rest_url( sprintf( 'wp/v2/%s/%d', $rest_base, $menu_item->object_id ) ); + $links['https://api.w.org/object'][] = array( + 'href' => $url, + 'taxonomy' => $menu_item->type, + 'embeddable' => true, + ); + } + } + + return $links; + } + + /** + * Retrieve Link Description Objects that should be added to the Schema for the posts collection. + * + * @return array + */ + protected function get_schema_links() { + $links = parent::get_schema_links(); + $href = rest_url( "{$this->namespace}/{$this->rest_base}/{id}" ); + $links[] = array( + 'rel' => 'https://api.w.org/object', + 'title' => __( 'Get linked object.', 'gutenberg' ), + 'href' => $href, + 'targetSchema' => array( + 'type' => 'object', + 'properties' => array( + 'object' => array( + 'type' => 'integer', + ), + ), + ), + ); + + return $links; + } + + /** + * Retrieves the term's schema, conforming to JSON Schema. + * + * @return array Item schema data. + */ + public function get_item_schema() { + $schema = array( + '$schema' => 'http://json-schema.org/draft-04/schema#', + 'title' => $this->post_type, + 'type' => 'object', + ); + + $schema['properties']['title'] = array( + 'description' => __( 'The title for the object.', 'gutenberg' ), + 'type' => 'object', + 'context' => array( 'view', 'edit', 'embed' ), + 'arg_options' => array( + // Note: sanitization implemented in self::prepare_item_for_database(). + 'sanitize_callback' => null, + // Note: validation implemented in self::prepare_item_for_database(). + 'validate_callback' => null, + ), + 'properties' => array( + 'raw' => array( + 'description' => __( 'Title for the object, as it exists in the database.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'edit' ), + ), + 'rendered' => array( + 'description' => __( 'HTML title for the object, transformed for display.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'view', 'edit', 'embed' ), + 'readonly' => true, + ), + ), + ); + + $schema['properties']['id'] = array( + 'description' => __( 'Unique identifier for the object.', 'gutenberg' ), + 'type' => 'integer', + 'default' => 0, + 'minimum' => 0, + 'context' => array( 'view', 'edit', 'embed' ), + 'readonly' => true, + ); + + $schema['properties']['type_label'] = array( + 'description' => __( 'Name of type.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'view', 'edit', 'embed' ), + 'readonly' => true, + ); + + $schema['properties']['type'] = array( + 'description' => __( 'The family of objects originally represented, such as "post_type" or "taxonomy".', 'gutenberg' ), + 'type' => 'string', + 'enum' => array( 'taxonomy', 'post_type', 'post_type_archive', 'custom' ), + 'context' => array( 'view', 'edit', 'embed' ), + 'default' => 'custom', + ); + + $schema['properties']['status'] = array( + 'description' => __( 'A named status for the object.', 'gutenberg' ), + 'type' => 'string', + 'enum' => array_keys( get_post_stati( array( 'internal' => false ) ) ), + 'default' => 'publish', + 'context' => array( 'view', 'edit', 'embed' ), + ); + + $schema['properties']['parent'] = array( + 'description' => __( 'The ID for the parent of the object.', 'gutenberg' ), + 'type' => 'integer', + 'minimum' => 0, + 'default' => 0, + 'context' => array( 'view', 'edit', 'embed' ), + ); + + $schema['properties']['attr_title'] = array( + 'description' => __( 'Text for the title attribute of the link element for this menu item.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'view', 'edit', 'embed' ), + 'arg_options' => array( + 'sanitize_callback' => 'sanitize_text_field', + ), + ); + + $schema['properties']['classes'] = array( + 'description' => __( 'Class names for the link element of this menu item.', 'gutenberg' ), + 'type' => 'array', + 'items' => array( + 'type' => 'string', + ), + 'context' => array( 'view', 'edit', 'embed' ), + 'arg_options' => array( + 'sanitize_callback' => function ( $value ) { + return array_map( 'sanitize_html_class', wp_parse_list( $value ) ); + }, + ), + ); + + $schema['properties']['description'] = array( + 'description' => __( 'The description of this menu item.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'view', 'edit', 'embed' ), + 'arg_options' => array( + 'sanitize_callback' => 'sanitize_text_field', + ), + ); + + $schema['properties']['menu_order'] = array( + 'description' => __( 'The DB ID of the nav_menu_item that is this item\'s menu parent, if any . 0 otherwise . ', 'gutenberg' ), + 'context' => array( 'view', 'edit', 'embed' ), + 'type' => 'integer', + 'minimum' => 0, + 'default' => 0, + ); + $schema['properties']['object'] = array( + 'description' => __( 'The type of object originally represented, such as "category," "post", or "attachment."', 'gutenberg' ), + 'context' => array( 'view', 'edit', 'embed' ), + 'type' => 'string', + ); + + $schema['properties']['object_id'] = array( + 'description' => __( 'The DB ID of the original object this menu item represents, e . g . ID for posts and term_id for categories .', 'gutenberg' ), + 'context' => array( 'view', 'edit', 'embed' ), + 'type' => 'integer', + 'minimum' => 0, + 'default' => 0, + ); + + $schema['properties']['target'] = array( + 'description' => __( 'The target attribute of the link element for this menu item.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'view', 'edit', 'embed' ), + 'enum' => array( + '_blank', + '', + ), + ); + + $schema['properties']['type_label'] = array( + 'description' => __( 'The singular label used to describe this type of menu item.', 'gutenberg' ), + 'context' => array( 'view', 'edit', 'embed' ), + 'type' => 'string', + 'readonly' => true, + ); + + $schema['properties']['url'] = array( + 'description' => __( 'The URL to which this menu item points.', 'gutenberg' ), + 'type' => 'string', + 'format' => 'uri', + 'context' => array( 'view', 'edit', 'embed' ), + ); + + $schema['properties']['xfn'] = array( + 'description' => __( 'The XFN relationship expressed in the link of this menu item.', 'gutenberg' ), + 'type' => 'array', + 'items' => array( + 'type' => 'string', + ), + 'context' => array( 'view', 'edit', 'embed' ), + 'arg_options' => array( + 'sanitize_callback' => function ( $value ) { + return array_map( 'sanitize_html_class', wp_parse_list( $value ) ); + }, + ), + ); + + $schema['properties']['_invalid'] = array( + 'description' => __( 'Whether the menu item represents an object that no longer exists .', 'gutenberg' ), + 'context' => array( 'view', 'edit', 'embed' ), + 'type' => 'boolean', + 'readonly' => true, + ); + + $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); + + foreach ( $taxonomies as $taxonomy ) { + $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; + $schema['properties'][ $base ] = array( + /* translators: %s: taxonomy name */ + 'description' => sprintf( __( 'The terms assigned to the object in the %s taxonomy.', 'gutenberg' ), $taxonomy->name ), + 'type' => 'array', + 'items' => array( + 'type' => 'integer', + ), + 'context' => array( 'view', 'edit' ), + ); + + if ( 'nav_menu' === $taxonomy->name ) { + $schema['properties'][ $base ]['type'] = 'integer'; + unset( $schema['properties'][ $base ]['items'] ); + } + } + + $schema['properties']['meta'] = $this->meta->get_field_schema(); + + $schema_links = $this->get_schema_links(); + + if ( $schema_links ) { + $schema['links'] = $schema_links; + } + + return $this->add_additional_fields_schema( $schema ); + } + + /** + * Retrieves the query params for the posts collection. + * + * @return array Collection parameters. + */ + public function get_collection_params() { + $query_params = parent::get_collection_params(); + + $query_params['menu_order'] = array( + 'description' => __( 'Limit result set to posts with a specific menu_order value.', 'gutenberg' ), + 'type' => 'integer', + ); + + $query_params['order'] = array( + 'description' => __( 'Order sort attribute ascending or descending.', 'gutenberg' ), + 'type' => 'string', + 'default' => 'asc', + 'enum' => array( 'asc', 'desc' ), + ); + + $query_params['orderby'] = array( + 'description' => __( 'Sort collection by object attribute.', 'gutenberg' ), + 'type' => 'string', + 'default' => 'menu_order', + 'enum' => array( + 'author', + 'date', + 'id', + 'include', + 'modified', + 'parent', + 'relevance', + 'slug', + 'include_slugs', + 'title', + 'menu_order', + ), + ); + + return $query_params; + } + + /** + * Determines the allowed query_vars for a get_items() response and prepares + * them for WP_Query. + * + * @param array $prepared_args Optional. Prepared WP_Query arguments. Default empty array. + * @param WP_REST_Request $request Optional. Full details about the request. + * + * @return array Items query arguments. + */ + protected function prepare_items_query( $prepared_args = array(), $request = null ) { + $query_args = parent::prepare_items_query( $prepared_args, $request ); + + // Map to proper WP_Query orderby param. + if ( isset( $query_args['orderby'] ) && isset( $request['orderby'] ) ) { + $orderby_mappings = array( + 'id' => 'ID', + 'include' => 'post__in', + 'slug' => 'post_name', + 'include_slugs' => 'post_name__in', + 'menu_order' => 'menu_order', + ); + + if ( isset( $orderby_mappings[ $request['orderby'] ] ) ) { + $query_args['orderby'] = $orderby_mappings[ $request['orderby'] ]; + } + } + + return $query_args; + } + + /** + * Checks whether current user can assign all terms sent with the current request. + * + * @param WP_REST_Request $request The request object with post and terms data. + * + * @return bool Whether the current user can assign the provided terms. + */ + protected function check_assign_terms_permission( $request ) { + $taxonomies = wp_list_filter( get_object_taxonomies( $this->post_type, 'objects' ), array( 'show_in_rest' => true ) ); + foreach ( $taxonomies as $taxonomy ) { + $base = ! empty( $taxonomy->rest_base ) ? $taxonomy->rest_base : $taxonomy->name; + + if ( ! isset( $request[ $base ] ) ) { + continue; + } + + foreach ( (array) $request[ $base ] as $term_id ) { + if ( ! $term_id ) { + continue; + } + + // Invalid terms will be rejected later. + if ( ! get_term( $term_id, $taxonomy->name ) ) { + continue; + }; + + if ( ! current_user_can( 'assign_term', (int) $term_id ) ) { + return false; + } + } + } + + return true; + } + + /** + * Get menu id of current menu item. + * + * @param int $menu_item_id Menu item id. + * + * @return int + */ + protected function get_menu_id( $menu_item_id ) { + $menu_ids = wp_get_post_terms( $menu_item_id, 'nav_menu', array( 'fields' => 'ids' ) ); + $menu_id = 0; + if ( $menu_ids && ! is_wp_error( $menu_ids ) ) { + $menu_id = array_shift( $menu_ids ); + } + + return $menu_id; + } +} diff --git a/lib/class-wp-rest-menu-locations-controller.php b/lib/class-wp-rest-menu-locations-controller.php new file mode 100644 index 00000000000000..d5df276c03c6ae --- /dev/null +++ b/lib/class-wp-rest-menu-locations-controller.php @@ -0,0 +1,264 @@ +namespace = '__experimental'; + $this->rest_base = 'menu-locations'; + } + + /** + * Registers the routes for the objects of the controller. + * + * @see register_rest_route() + */ + public function register_routes() { + register_rest_route( + $this->namespace, + '/' . $this->rest_base, + array( + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => array( $this, 'get_items' ), + 'permission_callback' => array( $this, 'get_items_permissions_check' ), + 'args' => $this->get_collection_params(), + ), + 'schema' => array( $this, 'get_public_item_schema' ), + ) + ); + + register_rest_route( + $this->namespace, + '/' . $this->rest_base . '/(?P[\w-]+)', + array( + 'args' => array( + 'location' => array( + 'description' => __( 'An alphanumeric identifier for the menu location.', 'gutenberg' ), + 'type' => 'string', + ), + ), + array( + 'methods' => WP_REST_Server::READABLE, + 'callback' => array( $this, 'get_item' ), + 'permission_callback' => array( $this, 'get_item_permissions_check' ), + 'args' => array( + 'context' => $this->get_context_param( array( 'default' => 'view' ) ), + ), + ), + 'schema' => array( $this, 'get_public_item_schema' ), + ) + ); + } + + /** + * Checks whether a given request has permission to read menu locations. + * + * @param WP_REST_Request $request Full details about the request. + * + * @return WP_Error|bool True if the request has read access, WP_Error object otherwise. + */ + public function get_items_permissions_check( $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable + if ( ! current_user_can( 'edit_theme_options' ) ) { + return new WP_Error( 'rest_cannot_view', __( 'Sorry, you are not allowed to view menu locations.', 'gutenberg' ), array( 'status' => rest_authorization_required_code() ) ); + } + + return true; + } + + /** + * Retrieves all menu locations, depending on user context. + * + * @param WP_REST_Request $request Full details about the request. + * + * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. + */ + public function get_items( $request ) { + $data = array(); + + foreach ( get_registered_nav_menus() as $name => $description ) { + $location = new stdClass(); + $location->name = $name; + $location->description = $description; + + $location = $this->prepare_item_for_response( $location, $request ); + $data[ $name ] = $this->prepare_response_for_collection( $location ); + } + + return rest_ensure_response( $data ); + } + + /** + * Checks if a given request has access to read a menu location. + * + * @param WP_REST_Request $request Full details about the request. + * + * @return WP_Error|bool True if the request has read access for the item, WP_Error object otherwise. + */ + public function get_item_permissions_check( $request ) { + if ( ! current_user_can( 'edit_theme_options' ) ) { + return new WP_Error( 'rest_cannot_view', __( 'Sorry, you are not allowed to view menu locations.', 'gutenberg' ), array( 'status' => rest_authorization_required_code() ) ); + } + if ( ! array_key_exists( $request['location'], get_registered_nav_menus() ) ) { + return new WP_Error( 'rest_menu_location_invalid', __( 'Invalid menu location.', 'gutenberg' ), array( 'status' => 404 ) ); + } + + return true; + } + + /** + * Retrieves a specific menu location. + * + * @param WP_REST_Request $request Full details about the request. + * + * @return WP_Error|WP_REST_Response Response object on success, or WP_Error object on failure. + */ + public function get_item( $request ) { + $registered_menus = get_registered_nav_menus(); + if ( ! array_key_exists( $request['location'], $registered_menus ) ) { + return new WP_Error( 'rest_menu_location_invalid', __( 'Invalid menu location.', 'gutenberg' ), array( 'status' => 404 ) ); + } + + $location = new stdClass(); + $location->name = $request['location']; + $location->description = $registered_menus[ $location->name ]; + + $data = $this->prepare_item_for_response( $location, $request ); + + return rest_ensure_response( $data ); + } + + /** + * Prepares a menu location object for serialization. + * + * @param stdClass $location Post status data. + * @param WP_REST_Request $request Full details about the request. + * + * @return WP_REST_Response Post status data. + */ + public function prepare_item_for_response( $location, $request ) { + $locations = get_nav_menu_locations(); + $menu = ( isset( $locations[ $location->name ] ) ) ? $locations[ $location->name ] : 0; + $data = array( + 'name' => $location->name, + 'description' => $location->description, + 'menu' => $menu, + ); + + $context = ! empty( $request['context'] ) ? $request['context'] : 'view'; + $data = $this->add_additional_fields_to_object( $data, $request ); + $data = $this->filter_response_by_context( $data, $context ); + + $response = rest_ensure_response( $data ); + + $response->add_links( $this->prepare_links( $location ) ); + + /** + * Filters a menu location returned from the REST API. + * + * Allows modification of the menu location data right before it is + * returned. + * + * @param WP_REST_Response $response The response object. + * @param object $location The original status object. + * @param WP_REST_Request $request Request used to generate the response. + */ + return apply_filters( 'rest_prepare_menu_location', $response, $location, $request ); + } + + /** + * Retrieves the menu location's schema, conforming to JSON Schema. + * + * @return array Item schema data. + */ + public function get_item_schema() { + $schema = array( + '$schema' => 'http://json-schema.org/draft-04/schema#', + 'title' => 'menu-location', + 'type' => 'object', + 'properties' => array( + 'name' => array( + 'description' => __( 'The name of the menu location.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'embed', 'view', 'edit' ), + 'readonly' => true, + ), + 'description' => array( + 'description' => __( 'The description of the menu location.', 'gutenberg' ), + 'type' => 'string', + 'context' => array( 'embed', 'view', 'edit' ), + 'readonly' => true, + ), + 'menu' => array( + 'description' => __( 'The ID of the assigned menu.', 'gutenberg' ), + 'type' => 'integer', + 'context' => array( 'embed', 'view', 'edit' ), + 'readonly' => true, + ), + ), + ); + + return $this->add_additional_fields_schema( $schema ); + } + + /** + * Retrieves the query params for collections. + * + * @return array Collection parameters. + */ + public function get_collection_params() { + return array( + 'context' => $this->get_context_param( array( 'default' => 'view' ) ), + ); + } + + /** + * Prepares links for the request. + * + * @param stdClass $location Menu location. + * + * @return array Links for the given menu location. + */ + protected function prepare_links( $location ) { + $base = sprintf( '%s/%s', $this->namespace, $this->rest_base ); + + // Entity meta. + $links = array( + 'self' => array( + 'href' => rest_url( trailingslashit( $base ) . $location->name ), + ), + 'collection' => array( + 'href' => rest_url( $base ), + ), + ); + + $locations = get_nav_menu_locations(); + $menu = ( isset( $locations[ $location->name ] ) ) ? $locations[ $location->name ] : 0; + if ( $menu ) { + $taxonomy_object = get_taxonomy( 'nav_menu' ); + if ( $taxonomy_object->show_in_rest ) { + $rest_base = ! empty( $taxonomy_object->rest_base ) ? $taxonomy_object->rest_base : $taxonomy_object->name; + $url = rest_url( sprintf( '__experimental/%s/%d', $rest_base, $menu ) ); + $links['https://api.w.org/menu'][] = array( + 'href' => $url, + 'embeddable' => true, + ); + } + } + + return $links; + } +} diff --git a/lib/class-wp-rest-menus-controller.php b/lib/class-wp-rest-menus-controller.php new file mode 100644 index 00000000000000..2c0a782f8ed212 --- /dev/null +++ b/lib/class-wp-rest-menus-controller.php @@ -0,0 +1,490 @@ +namespace = '__experimental'; + } + + /** + * Checks if a request has access to read terms in the specified taxonomy. + * + * @param WP_REST_Request $request Full details about the request. + * @return bool|WP_Error True if the request has read access, otherwise false or WP_Error object. + */ + public function get_items_permissions_check( $request ) { + $tax_obj = get_taxonomy( $this->taxonomy ); + if ( ! $tax_obj || ! $this->check_is_taxonomy_allowed( $this->taxonomy ) ) { + return false; + } + if ( ! current_user_can( $tax_obj->cap->edit_terms ) ) { + if ( 'edit' === $request['context'] ) { + return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit terms in this taxonomy.', 'gutenberg' ), array( 'status' => rest_authorization_required_code() ) ); + } + return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot view these menus, unless you have access to permission edit them. ', 'gutenberg' ), array( 'status' => rest_authorization_required_code() ) ); + } + return true; + } + + /** + * Checks if a request has access to read or edit the specified menu. + * + * @param WP_REST_Request $request Full details about the request. + * @return bool|WP_Error True if the request has read access for the item, otherwise false or WP_Error object. + */ + public function get_item_permissions_check( $request ) { + $term = $this->get_term( $request['id'] ); + if ( is_wp_error( $term ) ) { + return $term; + } + if ( ! current_user_can( 'edit_term', $term->term_id ) ) { + if ( 'edit' === $request['context'] ) { + return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit this term.', 'gutenberg' ), array( 'status' => rest_authorization_required_code() ) ); + } + return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot view this menu, unless you have access to permission edit it. ', 'gutenberg' ), array( 'status' => rest_authorization_required_code() ) ); + } + return true; + } + + /** + * Get the term, if the ID is valid. + * + * @param int $id Supplied ID. + * + * @return WP_Term|WP_Error Term object if ID is valid, WP_Error otherwise. + */ + protected function get_term( $id ) { + $term = parent::get_term( $id ); + + if ( is_wp_error( $term ) ) { + return $term; + } + + $nav_term = wp_get_nav_menu_object( $term ); + + return $nav_term; + } + + /** + * Checks if a request has access to create a term. + * Also check if request can assign menu locations. + * + * @param WP_REST_Request $request Full details about the request. + * + * @return bool|WP_Error True if the request has access to create items, false or WP_Error object otherwise. + */ + public function create_item_permissions_check( $request ) { + $check = $this->check_assign_locations_permission( $request ); + if ( is_wp_error( $check ) ) { + return $check; + } + + return parent::create_item_permissions_check( $request ); + } + + /** + * Checks if a request has access to update the specified term. + * + * @param WP_REST_Request $request Full details about the request. + * + * @return bool|WP_Error True if the request has access to update the item, false or WP_Error object otherwise. + */ + public function update_item_permissions_check( $request ) { + $check = $this->check_assign_locations_permission( $request ); + if ( is_wp_error( $check ) ) { + return $check; + } + + return parent::update_item_permissions_check( $request ); + } + + /** + * Checks whether current user can assign all locations sent with the current request. + * + * @param WP_REST_Request $request The request object with post and locations data. + * + * @return bool Whether the current user can assign the provided terms. + */ + protected function check_assign_locations_permission( $request ) { + if ( ! isset( $request['locations'] ) ) { + return true; + } + + if ( ! current_user_can( 'edit_theme_options' ) ) { + return new WP_Error( 'rest_cannot_assign_location', __( 'Sorry, you are not allowed to assign the provided locations.', 'gutenberg' ), array( 'status' => rest_authorization_required_code() ) ); + } + + foreach ( $request['locations'] as $location ) { + if ( ! array_key_exists( $location, get_registered_nav_menus() ) ) { + return new WP_Error( + 'rest_menu_location_invalid', + __( 'Invalid menu location.', 'gutenberg' ), + array( + 'status' => 400, + 'location' => $location, + ) + ); + } + } + + return true; + } + + /** + * Prepares a single term output for response. + * + * @param obj $term Term object. + * @param WP_REST_Request $request Request object. + * + * @return WP_REST_Response $response Response object. + */ + public function prepare_item_for_response( $term, $request ) { + $nav_menu = wp_get_nav_menu_object( $term ); + + return parent::prepare_item_for_response( $nav_menu, $request ); + } + + /** + * Prepares links for the request. + * + * @param object $term Term object. + * + * @return array Links for the given term. + */ + protected function prepare_links( $term ) { + $links = parent::prepare_links( $term ); + + $locations = get_nav_menu_locations(); + $rest_base = 'menu-locations'; + foreach ( $locations as $menu_name => $menu_id ) { + if ( $term->term_id === $menu_id ) { + $url = rest_url( sprintf( '__experimental/%s/%s', $rest_base, $menu_name ) ); + $links['https://api.w.org/menu-location'][] = array( + 'href' => $url, + 'embeddable' => true, + ); + } + } + + return $links; + } + + /** + * Prepares a single term for create or update. + * + * @param WP_REST_Request $request Request object. + * + * @return array $prepared_term Term object. + */ + public function prepare_item_for_database( $request ) { + $prepared_term = parent::prepare_item_for_database( $request ); + + $prepared_term = (array) $prepared_term; + $schema = $this->get_item_schema(); + if ( isset( $request['name'] ) && ! empty( $schema['properties']['name'] ) ) { + $prepared_term['menu-name'] = $request['name']; + } + + return $prepared_term; + } + + /** + * Creates a single term in a taxonomy. + * + * @param WP_REST_Request $request Full details about the request. + * + * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. + */ + public function create_item( $request ) { + if ( isset( $request['parent'] ) ) { + if ( ! is_taxonomy_hierarchical( $this->taxonomy ) ) { + return new WP_Error( 'rest_taxonomy_not_hierarchical', __( 'Cannot set parent term, taxonomy is not hierarchical.', 'gutenberg' ), array( 'status' => 400 ) ); + } + + $parent = wp_get_nav_menu_object( (int) $request['parent'] ); + + if ( ! $parent ) { + return new WP_Error( 'rest_term_invalid', __( 'Parent term does not exist.', 'gutenberg' ), array( 'status' => 400 ) ); + } + } + + $prepared_term = $this->prepare_item_for_database( $request ); + + $term = wp_update_nav_menu_object( 0, wp_slash( (array) $prepared_term ) ); + + if ( is_wp_error( $term ) ) { + /* + * If we're going to inform the client that the term already exists, + * give them the identifier for future use. + */ + $term_id = $term->get_error_data( 'term_exists' ); + if ( $term_id ) { + $existing_term = get_term( $term_id, $this->taxonomy ); + $term->add_data( $existing_term->term_id, 'term_exists' ); + $term->add_data( + array( + 'status' => 400, + 'term_id' => $term_id, + ) + ); + } + + return $term; + } + + $term = $this->get_term( $term ); + + /** + * Fires after a single term is created or updated via the REST API. + * + * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug. + * + * @param WP_Term $term Inserted or updated term object. + * @param WP_REST_Request $request Request object. + * @param bool $creating True when creating a term, false when updating. + */ + do_action( "rest_insert_{$this->taxonomy}", $term, $request, true ); + + $schema = $this->get_item_schema(); + if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { + $meta_update = $this->meta->update_value( $request['meta'], $term->term_id ); + + if ( is_wp_error( $meta_update ) ) { + return $meta_update; + } + } + + $locations_update = $this->handle_locations( $term->term_id, $request ); + + if ( is_wp_error( $locations_update ) ) { + return $locations_update; + } + + $fields_update = $this->update_additional_fields_for_object( $term, $request ); + + if ( is_wp_error( $fields_update ) ) { + return $fields_update; + } + + $request->set_param( 'context', 'view' ); + + /** + * Fires after a single term is completely created or updated via the REST API. + * + * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug. + * + * @param WP_Term $term Inserted or updated term object. + * @param WP_REST_Request $request Request object. + * @param bool $creating True when creating a term, false when updating. + * + * @since 5.0.0 + */ + do_action( "rest_after_insert_{$this->taxonomy}", $term, $request, true ); + + $response = $this->prepare_item_for_response( $term, $request ); + $response = rest_ensure_response( $response ); + + $response->set_status( 201 ); + $response->header( 'Location', rest_url( $this->namespace . '/' . $this->rest_base . '/' . $term->term_id ) ); + + return $response; + } + + /** + * Updates a single term from a taxonomy. + * + * @param WP_REST_Request $request Full details about the request. + * + * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. + */ + public function update_item( $request ) { + $term = $this->get_term( $request['id'] ); + if ( is_wp_error( $term ) ) { + return $term; + } + + if ( isset( $request['parent'] ) ) { + if ( ! is_taxonomy_hierarchical( $this->taxonomy ) ) { + return new WP_Error( 'rest_taxonomy_not_hierarchical', __( 'Cannot set parent term, taxonomy is not hierarchical.', 'gutenberg' ), array( 'status' => 400 ) ); + } + + $parent = get_term( (int) $request['parent'], $this->taxonomy ); + + if ( ! $parent ) { + return new WP_Error( 'rest_term_invalid', __( 'Parent term does not exist.', 'gutenberg' ), array( 'status' => 400 ) ); + } + } + + $prepared_term = $this->prepare_item_for_database( $request ); + + // Only update the term if we haz something to update. + if ( ! empty( $prepared_term ) ) { + $update = wp_update_nav_menu_object( $term->term_id, wp_slash( (array) $prepared_term ) ); + + if ( is_wp_error( $update ) ) { + return $update; + } + } + + $term = get_term( $term->term_id, $this->taxonomy ); + + /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */ + do_action( "rest_insert_{$this->taxonomy}", $term, $request, false ); + + $schema = $this->get_item_schema(); + if ( ! empty( $schema['properties']['meta'] ) && isset( $request['meta'] ) ) { + $meta_update = $this->meta->update_value( $request['meta'], $term->term_id ); + + if ( is_wp_error( $meta_update ) ) { + return $meta_update; + } + } + + $locations_update = $this->handle_locations( $term->term_id, $request ); + + if ( is_wp_error( $locations_update ) ) { + return $locations_update; + } + + $fields_update = $this->update_additional_fields_for_object( $term, $request ); + + if ( is_wp_error( $fields_update ) ) { + return $fields_update; + } + + $request->set_param( 'context', 'view' ); + + /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-terms-controller.php */ + do_action( "rest_after_insert_{$this->taxonomy}", $term, $request, false ); + + $response = $this->prepare_item_for_response( $term, $request ); + + return rest_ensure_response( $response ); + } + + /** + * Deletes a single term from a taxonomy. + * + * @param WP_REST_Request $request Full details about the request. + * + * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. + */ + public function delete_item( $request ) { + $term = $this->get_term( $request['id'] ); + if ( is_wp_error( $term ) ) { + return $term; + } + + $force = isset( $request['force'] ) ? (bool) $request['force'] : false; + + // We don't support trashing for terms. + if ( ! $force ) { + /* translators: %s: force=true */ + return new WP_Error( 'rest_trash_not_supported', sprintf( __( "Terms do not support trashing. Set '%s' to delete.", 'gutenberg' ), 'force=true' ), array( 'status' => 501 ) ); + } + + $request->set_param( 'context', 'view' ); + + $previous = $this->prepare_item_for_response( $term, $request ); + + $retval = wp_delete_nav_menu( $term ); + + if ( ! $retval ) { + return new WP_Error( 'rest_cannot_delete', __( 'The term cannot be deleted.', 'gutenberg' ), array( 'status' => 500 ) ); + } + + $response = new WP_REST_Response(); + $response->set_data( + array( + 'deleted' => true, + 'previous' => $previous->get_data(), + ) + ); + + /** + * Fires after a single term is deleted via the REST API. + * + * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug. + * + * @param WP_Term $term The deleted term. + * @param WP_REST_Response $response The response data. + * @param WP_REST_Request $request The request sent to the API. + */ + do_action( "rest_delete_{$this->taxonomy}", $term, $response, $request ); + + return $response; + } + + /** + * Updates the menu's locations from a REST request. + * + * @param int $menu_id The menu id to update the location form. + * @param WP_REST_Request $request The request object with menu and locations data. + * + * @return true|WP_Error WP_Error on an error assigning any of the locations, otherwise null. + */ + protected function handle_locations( $menu_id, $request ) { + if ( ! isset( $request['locations'] ) ) { + return true; + } + + $menu_locations = get_registered_nav_menus(); + $menu_locations = array_keys( $menu_locations ); + $new_locations = array(); + foreach ( $request['locations'] as $location ) { + if ( ! in_array( $location, $menu_locations, true ) ) { + return new WP_Error( 'invalid_menu_location', __( 'Menu location does not exist.', 'gutenberg' ), array( 'status' => 400 ) ); + } + $new_locations[ $location ] = $menu_id; + } + $assigned_menu = get_nav_menu_locations(); + foreach ( $assigned_menu as $location => $term_id ) { + if ( $term_id === $menu_id ) { + unset( $assigned_menu[ $location ] ); + } + } + $new_assignments = array_merge( $assigned_menu, $new_locations ); + set_theme_mod( 'nav_menu_locations', $new_assignments ); + + return true; + } + + /** + * Retrieves the term's schema, conforming to JSON Schema. + * + * @return array Item schema data. + */ + public function get_item_schema() { + $schema = parent::get_item_schema(); + unset( $schema['properties']['count'] ); + unset( $schema['properties']['link'] ); + unset( $schema['properties']['taxonomy'] ); + + $schema['properties']['locations'] = array( + 'description' => __( 'The locations assigned to the menu.', 'gutenberg' ), + 'type' => 'array', + 'items' => array( + 'type' => 'string', + ), + 'context' => array( 'view', 'edit' ), + ); + + return $schema; + } +} diff --git a/lib/load.php b/lib/load.php index 5b641a13278d1e..f1037f11d36be2 100644 --- a/lib/load.php +++ b/lib/load.php @@ -39,6 +39,15 @@ function gutenberg_is_experiment_enabled( $name ) { if ( ! class_exists( 'WP_REST_Block_Directory_Controller' ) ) { require dirname( __FILE__ ) . '/class-wp-rest-block-directory-controller.php'; } + if ( ! class_exists( 'WP_REST_Menus_Controller' ) ) { + require_once dirname( __FILE__ ) . '/class-wp-rest-menus-controller.php'; + } + if ( ! class_exists( 'WP_REST_Menu_Items_Controller' ) ) { + require_once dirname( __FILE__ ) . '/class-wp-rest-menu-items-controller.php'; + } + if ( ! class_exists( 'WP_REST_Menu_Locations_Controller' ) ) { + require_once dirname( __FILE__ ) . '/class-wp-rest-menu-locations-controller.php'; + } /** * End: Include for phase 2 */ diff --git a/lib/rest-api.php b/lib/rest-api.php index e0b6e7be592e7b..8a4a8a80a3b8ce 100644 --- a/lib/rest-api.php +++ b/lib/rest-api.php @@ -93,3 +93,49 @@ function gutenberg_register_rest_block_directory() { $block_directory_controller->register_routes(); } add_filter( 'rest_api_init', 'gutenberg_register_rest_block_directory' ); + +/** + * Registers the menu locations area REST API routes. + */ +function gutenberg_register_rest_menu_location() { + $nav_menu_location = new WP_REST_Menu_Locations_Controller(); + $nav_menu_location->register_routes(); +} +add_action( 'rest_api_init', 'gutenberg_register_rest_menu_location' ); +/** + * Hook in to the nav menu item post type and enable a post type rest endpoint. + * + * @param array $args Current registered post type args. + * @param string $post_type Name of post type. + * + * @return array + */ +function wp_api_nav_menus_post_type_args( $args, $post_type ) { + if ( 'nav_menu_item' === $post_type ) { + $args['show_in_rest'] = true; + $args['rest_base'] = 'menu-items'; + $args['rest_controller_class'] = 'WP_REST_Menu_Items_Controller'; + } + + return $args; +} +add_filter( 'register_post_type_args', 'wp_api_nav_menus_post_type_args', 10, 2 ); + +/** + * Hook in to the nav_menu taxonomy and enable a taxonomy rest endpoint. + * + * @param array $args Current registered taxonomy args. + * @param string $taxonomy Name of taxonomy. + * + * @return array + */ +function wp_api_nav_menus_taxonomy_args( $args, $taxonomy ) { + if ( 'nav_menu' === $taxonomy ) { + $args['show_in_rest'] = true; + $args['rest_base'] = 'menus'; + $args['rest_controller_class'] = 'WP_REST_Menus_Controller'; + } + + return $args; +} +add_filter( 'register_taxonomy_args', 'wp_api_nav_menus_taxonomy_args', 10, 2 ); diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 87c4674f45e6e1..ce2c3a67a6a423 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -61,6 +61,9 @@ phpunit/* + + phpunit/* + phpunit/* diff --git a/phpunit/class-rest-nav-menu-items-controller-test.php b/phpunit/class-rest-nav-menu-items-controller-test.php new file mode 100644 index 00000000000000..a9c5ff444a7790 --- /dev/null +++ b/phpunit/class-rest-nav-menu-items-controller-test.php @@ -0,0 +1,817 @@ +user->create( + array( + 'role' => 'administrator', + ) + ); + self::$subscriber_id = $factory->user->create( + array( + 'role' => 'subscriber', + ) + ); + } + + /** + * + */ + public static function wpTearDownAfterClass() { + self::delete_user( self::$admin_id ); + self::delete_user( self::$subscriber_id ); + } + + /** + * + */ + public function setUp() { + parent::setUp(); + + $this->tag_id = self::factory()->tag->create(); + + $this->menu_id = wp_create_nav_menu( rand_str() ); + + $this->menu_item_id = wp_update_nav_menu_item( + $this->menu_id, + 0, + array( + 'menu-item-type' => 'taxonomy', + 'menu-item-object' => 'post_tag', + 'menu-item-object-id' => $this->tag_id, + 'menu-item-status' => 'publish', + ) + ); + } + + /** + * + */ + public function test_register_routes() { + $routes = rest_get_server()->get_routes(); + + $this->assertArrayHasKey( '/__experimental/menu-items', $routes ); + $this->assertCount( 2, $routes['/__experimental/menu-items'] ); + $this->assertArrayHasKey( '/__experimental/menu-items/(?P[\d]+)', $routes ); + $this->assertCount( 3, $routes['/__experimental/menu-items/(?P[\d]+)'] ); + } + + /** + * + */ + public function test_context_param() { + // Collection. + $request = new WP_REST_Request( 'OPTIONS', '/__experimental/menu-items' ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $this->assertEquals( 'view', $data['endpoints'][0]['args']['context']['default'] ); + $this->assertEquals( array( 'view', 'embed', 'edit' ), $data['endpoints'][0]['args']['context']['enum'] ); + // Single. + $request = new WP_REST_Request( 'OPTIONS', '/__experimental/menu-items/' . $this->menu_item_id ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $this->assertEquals( 'view', $data['endpoints'][0]['args']['context']['default'] ); + $this->assertEquals( array( 'view', 'embed', 'edit' ), $data['endpoints'][0]['args']['context']['enum'] ); + } + + /** + * + */ + public function test_registered_query_params() { + $request = new WP_REST_Request( 'OPTIONS', '/__experimental/menu-items' ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $properties = $data['endpoints'][0]['args']; + $this->assertArrayHasKey( 'before', $properties ); + $this->assertArrayHasKey( 'context', $properties ); + $this->assertArrayHasKey( 'exclude', $properties ); + $this->assertArrayHasKey( 'include', $properties ); + $this->assertArrayHasKey( 'menu_order', $properties ); + $this->assertArrayHasKey( 'menus', $properties ); + $this->assertArrayHasKey( 'menus_exclude', $properties ); + $this->assertArrayHasKey( 'offset', $properties ); + $this->assertArrayHasKey( 'order', $properties ); + $this->assertArrayHasKey( 'orderby', $properties ); + $this->assertArrayHasKey( 'page', $properties ); + $this->assertArrayHasKey( 'per_page', $properties ); + $this->assertArrayHasKey( 'search', $properties ); + $this->assertArrayHasKey( 'slug', $properties ); + $this->assertArrayHasKey( 'status', $properties ); + } + + /** + * + */ + public function test_registered_get_item_params() { + $request = new WP_REST_Request( 'OPTIONS', sprintf( '/__experimental/menu-items/%d', $this->menu_item_id ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $keys = array_keys( $data['endpoints'][0]['args'] ); + sort( $keys ); + $this->assertEquals( array( 'context', 'id' ), $keys ); + } + + /** + * + */ + public function test_get_items() { + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'GET', '/__experimental/menu-items' ); + $response = rest_get_server()->dispatch( $request ); + + $this->check_get_menu_items_response( $response ); + } + + /** + * + */ + public function test_get_item() { + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'GET', sprintf( '/__experimental/menu-items/%d', $this->menu_item_id ) ); + $response = rest_get_server()->dispatch( $request ); + + $this->check_get_menu_item_response( $response, 'view' ); + } + + /** + * + */ + public function test_create_item() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data(); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + + $this->check_create_menu_item_response( $response ); + } + + /** + * + */ + public function test_create_item_invalid_term() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'type' => 'taxonomy', + 'title' => 'Tags', + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_term_invalid_id', $response, 400 ); + } + + /** + * + */ + public function test_create_item_change_position() { + wp_set_current_user( self::$admin_id ); + $new_menu_id = wp_create_nav_menu( rand_str() ); + for ( $i = 1; $i < 5; $i ++ ) { + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'menus' => $new_menu_id, + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->check_create_menu_item_response( $response ); + $data = $response->get_data(); + $this->assertEquals( $data['menu_order'], $i ); + } + } + + /** + * + */ + public function test_create_item_invalid_position() { + wp_set_current_user( self::$admin_id ); + $new_menu_id = wp_create_nav_menu( rand_str() ); + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'menu_order' => 1, + 'menus' => $new_menu_id, + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->check_create_menu_item_response( $response ); + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'menu_order' => 1, + 'menus' => $new_menu_id, + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + + $this->assertErrorResponse( 'invalid_menu_order', $response, 400 ); + } + + /** + * + */ + public function test_create_item_invalid_position_2() { + wp_set_current_user( self::$admin_id ); + $new_menu_id = wp_create_nav_menu( rand_str() ); + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'menu_order' => 'ddddd', + 'menus' => $new_menu_id, + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_invalid_param', $response, 400 ); + } + + /** + * + */ + public function test_create_item_invalid_position_3() { + wp_set_current_user( self::$admin_id ); + $new_menu_id = wp_create_nav_menu( rand_str() ); + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'menu_order' => -9, + 'menus' => $new_menu_id, + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_invalid_param', $response, 400 ); + } + + /** + * + */ + public function test_create_item_invalid_parent() { + wp_set_current_user( self::$admin_id ); + wp_create_nav_menu( rand_str() ); + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'parent' => -9, + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_invalid_param', $response, 400 ); + } + + /** + * + */ + public function test_create_item_invalid_parent_menu_item() { + wp_set_current_user( self::$admin_id ); + $new_menu_id = wp_create_nav_menu( rand_str() ); + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'menus' => $new_menu_id, + 'parent' => $this->menu_item_id, + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'invalid_item_parent', $response, 400 ); + } + + /** + * + */ + public function test_create_item_invalid_parent_post() { + wp_set_current_user( self::$admin_id ); + $post_id = self::factory()->post->create(); + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'parent' => $post_id, + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'invalid_menu_item_parent', $response, 400 ); + } + + /** + * + */ + public function test_create_item_invalid_menu() { + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'menus' => -9, + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'invalid_menu_id', $response, 400 ); + } + + /** + * + */ + public function test_create_item_invalid_post() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'type' => 'post_type', + 'title' => 'Post', + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_post_invalid_id', $response, 400 ); + } + + /** + * + */ + public function test_create_item_invalid_post_type() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'type' => 'post_type_archive', + 'menu-item-object' => 'invalid_post_type', + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_post_invalid_type', $response, 400 ); + } + + /** + * + */ + public function test_create_item_invalid_custom_link() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'type' => 'custom', + 'title' => '', + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_title_required', $response, 400 ); + } + + /** + * + */ + public function test_create_item_invalid_custom_link_url() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/__experimental/menu-items' ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'type' => 'custom', + 'url' => '', + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_url_required', $response, 400 ); + } + + /** + * + */ + public function test_update_item() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'PUT', sprintf( '/__experimental/menu-items/%d', $this->menu_item_id ) ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'xfn' => array( 'test1', 'test2', 'test3' ), + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->check_update_menu_item_response( $response ); + $new_data = $response->get_data(); + $this->assertEquals( $this->menu_item_id, $new_data['id'] ); + $this->assertEquals( $params['title'], $new_data['title']['raw'] ); + $this->assertEquals( $params['description'], $new_data['description'] ); + $this->assertEquals( $params['type_label'], $new_data['type_label'] ); + $this->assertEquals( $params['xfn'], $new_data['xfn'] ); + $post = get_post( $this->menu_item_id ); + $menu_item = wp_setup_nav_menu_item( $post ); + $this->assertEquals( $params['title'], $menu_item->title ); + $this->assertEquals( $params['description'], $menu_item->description ); + $this->assertEquals( $params['xfn'], explode( ' ', $menu_item->xfn ) ); + } + + /** + * + */ + public function test_update_item_clean_xfn() { + wp_set_current_user( self::$admin_id ); + + $bad_data = array( 'test1":|":', 'test2+|+', 'test3±', 'test4😀' ); + $good_data = array( 'test1', 'test2', 'test3', 'test4' ); + + $request = new WP_REST_Request( 'PUT', sprintf( '/__experimental/menu-items/%d', $this->menu_item_id ) ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data( + array( + 'xfn' => $bad_data, + ) + ); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->check_update_menu_item_response( $response ); + $new_data = $response->get_data(); + $this->assertEquals( $this->menu_item_id, $new_data['id'] ); + $this->assertEquals( $params['title'], $new_data['title']['raw'] ); + $this->assertEquals( $params['description'], $new_data['description'] ); + $this->assertEquals( $params['type_label'], $new_data['type_label'] ); + $this->assertEquals( $good_data, $new_data['xfn'] ); + $post = get_post( $this->menu_item_id ); + $menu_item = wp_setup_nav_menu_item( $post ); + $this->assertEquals( $params['title'], $menu_item->title ); + $this->assertEquals( $params['description'], $menu_item->description ); + $this->assertEquals( $good_data, explode( ' ', $menu_item->xfn ) ); + } + + + /** + * + */ + public function test_update_item_invalid() { + wp_set_current_user( self::$admin_id ); + $post_id = self::factory()->post->create(); + + $request = new WP_REST_Request( 'PUT', sprintf( '/__experimental/menu-items/%d', $post_id ) ); + $request->add_header( 'content-type', 'application/x-www-form-urlencoded' ); + $params = $this->set_menu_item_data(); + $request->set_body_params( $params ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_post_invalid_id', $response, 404 ); + } + + /** + * + */ + public function test_delete_item() { + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'DELETE', sprintf( '/__experimental/menu-items/%d', $this->menu_item_id ) ); + $request->set_param( 'force', true ); + $response = rest_get_server()->dispatch( $request ); + $this->assertEquals( 200, $response->get_status() ); + $this->assertNull( get_post( $this->menu_item_id ) ); + } + + + /** + * + */ + public function test_delete_item_no_force() { + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'DELETE', sprintf( '/__experimental/menu-items/%d', $this->menu_item_id ) ); + $request->set_param( 'force', false ); + $response = rest_get_server()->dispatch( $request ); + $this->assertEquals( 501, $response->get_status() ); + $this->assertNotNull( get_post( $this->menu_item_id ) ); + } + + /** + * + */ + public function test_prepare_item() { + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'GET', '/__experimental/menu-items/' . $this->menu_item_id ); + $response = rest_get_server()->dispatch( $request ); + $this->assertEquals( 200, $response->get_status() ); + $this->check_get_menu_item_response( $response ); + } + + /** + * + */ + public function test_get_item_schema() { + $request = new WP_REST_Request( 'OPTIONS', '/__experimental/menu-items' ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $properties = $data['schema']['properties']; + $this->assertEquals( 18, count( $properties ) ); + $this->assertArrayHasKey( 'type_label', $properties ); + $this->assertArrayHasKey( 'attr_title', $properties ); + $this->assertArrayHasKey( 'classes', $properties ); + $this->assertArrayHasKey( 'description', $properties ); + $this->assertArrayHasKey( 'id', $properties ); + $this->assertArrayHasKey( 'url', $properties ); + $this->assertArrayHasKey( 'meta', $properties ); + $this->assertArrayHasKey( 'menu_order', $properties ); + $this->assertArrayHasKey( 'object', $properties ); + $this->assertArrayHasKey( 'object_id', $properties ); + $this->assertArrayHasKey( 'target', $properties ); + $this->assertArrayHasKey( 'parent', $properties ); + $this->assertArrayHasKey( 'status', $properties ); + $this->assertArrayHasKey( 'title', $properties ); + $this->assertArrayHasKey( 'type', $properties ); + $this->assertArrayHasKey( 'xfn', $properties ); + $this->assertArrayHasKey( '_invalid', $properties ); + } + + /** + * + */ + public function test_get_items_no_permission() { + wp_set_current_user( 0 ); + $request = new WP_REST_Request( 'GET', '/__experimental/menu-items' ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_cannot_view', $response, 401 ); + } + + /** + * + */ + public function test_get_item_no_permission() { + wp_set_current_user( 0 ); + $request = new WP_REST_Request( 'GET', '/__experimental/menu-items/' . $this->menu_item_id ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_cannot_view', $response, 401 ); + } + + /** + * + */ + public function test_get_items_wrong_permission() { + wp_set_current_user( self::$subscriber_id ); + $request = new WP_REST_Request( 'GET', '/__experimental/menu-items' ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_cannot_view', $response, 403 ); + } + + /** + * + */ + public function test_get_item_wrong_permission() { + wp_set_current_user( self::$subscriber_id ); + $request = new WP_REST_Request( 'GET', '/__experimental/menu-items/' . $this->menu_item_id ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_cannot_view', $response, 403 ); + } + + /** + * @param WP_REST_Response $response Response Class. + * @param string $context Defaults to View. + */ + protected function check_get_menu_items_response( $response, $context = 'view' ) { + $this->assertNotWPError( $response ); + $response = rest_ensure_response( $response ); + $this->assertEquals( 200, $response->get_status() ); + + $headers = $response->get_headers(); + $this->assertArrayHasKey( 'X-WP-Total', $headers ); + $this->assertArrayHasKey( 'X-WP-TotalPages', $headers ); + + $all_data = $response->get_data(); + foreach ( $all_data as $data ) { + $post = get_post( $data['id'] ); + // Base fields for every post. + $menu_item = wp_setup_nav_menu_item( $post ); + /** + * As the links for the post are "response_links" format in the data array we have to pull them out and parse them. + */ + $links = $data['_links']; + foreach ( $links as &$links_array ) { + foreach ( $links_array as &$link ) { + $attributes = array_diff_key( + $link, + array( + 'href' => 1, + 'name' => 1, + ) + ); + $link = array_diff_key( $link, $attributes ); + $link['attributes'] = $attributes; + } + } + + $this->check_menu_item_data( $menu_item, $data, $context, $links ); + } + } + + /** + * @param WP_Post $post WP_Post object. + * @param array $data Data compare. + * @param string $context Context of REST Request. + * @param array $links Array links. + */ + protected function check_menu_item_data( $post, $data, $context, $links ) { + $post_type_obj = get_post_type_object( self::POST_TYPE ); + + // Standard fields. + $this->assertEquals( $post->ID, $data['id'] ); + $this->assertEquals( wpautop( $post->post_content ), $data['description'] ); + + // Check filtered values. + if ( post_type_supports( self::POST_TYPE, 'title' ) ) { + add_filter( 'protected_title_format', array( $this, 'protected_title_format' ) ); + $this->assertEquals( $post->title, $data['title']['rendered'] ); + remove_filter( 'protected_title_format', array( $this, 'protected_title_format' ) ); + if ( 'edit' === $context ) { + $this->assertEquals( $post->post_title, $data['title']['raw'] ); + } else { + $this->assertFalse( isset( $data['title']['raw'] ) ); + } + } else { + $this->assertFalse( isset( $data['title'] ) ); + } + + // post_parent. + $this->assertArrayHasKey( 'parent', $data ); + if ( $post->post_parent ) { + if ( is_int( $data['parent'] ) ) { + $this->assertEquals( $post->post_parent, $data['parent'] ); + } else { + $this->assertEquals( $post->post_parent, $data['parent']['id'] ); + $menu_item = wp_setup_nav_menu_item( get_post( $data['parent']['id'] ) ); + $this->check_get_menu_item_response( $data['parent'], $menu_item, 'view-parent' ); + } + } else { + $this->assertEmpty( $data['parent'] ); + } + + // page attributes. + $this->assertEquals( $post->menu_order, $data['menu_order'] ); + + $taxonomies = wp_list_filter( get_object_taxonomies( self::POST_TYPE, 'objects' ), array( 'show_in_rest' => true ) ); + foreach ( $taxonomies as $taxonomy ) { + $this->assertTrue( isset( $data[ $taxonomy->rest_base ] ) ); + $terms = wp_get_object_terms( $post->ID, $taxonomy->name, array( 'fields' => 'ids' ) ); + sort( $terms ); + sort( $data[ $taxonomy->rest_base ] ); + $this->assertEquals( $terms, $data[ $taxonomy->rest_base ] ); + } + + // test links. + if ( $links ) { + $links = test_rest_expand_compact_links( $links ); + $this->assertEquals( $links['self'][0]['href'], rest_url( '__experimental/' . $post_type_obj->rest_base . '/' . $data['id'] ) ); + $this->assertEquals( $links['collection'][0]['href'], rest_url( '__experimental/' . $post_type_obj->rest_base ) ); + $this->assertEquals( $links['about'][0]['href'], rest_url( 'wp/v2/types/' . self::POST_TYPE ) ); + + $num = 0; + foreach ( $taxonomies as $key => $taxonomy ) { + $this->assertEquals( $taxonomy->name, $links['https://api.w.org/term'][ $num ]['attributes']['taxonomy'] ); + $this->assertEquals( add_query_arg( 'post', $data['id'], rest_url( 'wp/v2/' . $taxonomy->rest_base ) ), $links['https://api.w.org/term'][ $num ]['href'] ); + $num ++; + } + } + } + + /** + * @param WP_REST_Response $response Response Class. + * @param string $context Defaults to View. + */ + protected function check_get_menu_item_response( $response, $context = 'view' ) { + $this->assertNotWPError( $response ); + $response = rest_ensure_response( $response ); + $this->assertEquals( 200, $response->get_status() ); + + $data = $response->get_data(); + $post = get_post( $data['id'] ); + $menu_item = wp_setup_nav_menu_item( $post ); + $this->check_menu_item_data( $menu_item, $data, $context, $response->get_links() ); + } + + /** + * @param WP_REST_Response $response Response Class. + */ + protected function check_create_menu_item_response( $response ) { + $this->assertNotWPError( $response ); + $response = rest_ensure_response( $response ); + + $this->assertEquals( 201, $response->get_status() ); + $headers = $response->get_headers(); + $this->assertArrayHasKey( 'Location', $headers ); + + $data = $response->get_data(); + $post = get_post( $data['id'] ); + $menu_item = wp_setup_nav_menu_item( $post ); + $this->check_menu_item_data( $menu_item, $data, 'edit', $response->get_links() ); + } + + /** + * @param WP_REST_Response $response Response Class. + */ + protected function check_update_menu_item_response( $response ) { + $this->assertNotWPError( $response ); + $response = rest_ensure_response( $response ); + + $this->assertEquals( 200, $response->get_status() ); + $headers = $response->get_headers(); + $this->assertArrayNotHasKey( 'Location', $headers ); + + $data = $response->get_data(); + $post = get_post( $data['id'] ); + $menu_item = wp_setup_nav_menu_item( $post ); + $this->check_menu_item_data( $menu_item, $data, 'edit', $response->get_links() ); + } + + /** + * @param array $args Override params. + * + * @return mixed + */ + protected function set_menu_item_data( $args = array() ) { + $defaults = array( + 'object_id' => 0, + 'parent' => 0, + 'menu_order' => 0, + 'menus' => $this->menu_id, + 'type' => 'custom', + 'title' => 'Custom Link Title', + 'url' => '#', + 'description' => '', + 'attr-title' => '', + 'target' => '', + 'type_label' => 'Custom Link', + 'classes' => '', + 'xfn' => '', + 'status' => 'draft', + ); + + return wp_parse_args( $args, $defaults ); + } +} diff --git a/phpunit/class-rest-nav-menu-locations-test.php b/phpunit/class-rest-nav-menu-locations-test.php new file mode 100644 index 00000000000000..a1488aad65105e --- /dev/null +++ b/phpunit/class-rest-nav-menu-locations-test.php @@ -0,0 +1,180 @@ +user->create( + array( + 'role' => 'administrator', + ) + ); + } + + /** + * Set up. + */ + public function setUp() { + parent::setUp(); + + // Unregister all nav menu locations. + foreach ( array_keys( get_registered_nav_menus() ) as $location ) { + unregister_nav_menu( $location ); + } + } + + /** + * Register nav menu locations. + * + * @param array $locations Location slugs. + */ + public function register_nav_menu_locations( $locations ) { + foreach ( $locations as $location ) { + register_nav_menu( $location, ucfirst( $location ) ); + } + } + + /** + * + */ + public function test_register_routes() { + $routes = rest_get_server()->get_routes(); + $this->assertArrayHasKey( '/__experimental/menu-locations', $routes ); + $this->assertCount( 1, $routes['/__experimental/menu-locations'] ); + $this->assertArrayHasKey( '/__experimental/menu-locations/(?P[\w-]+)', $routes ); + $this->assertCount( 1, $routes['/__experimental/menu-locations/(?P[\w-]+)'] ); + } + + /** + * + */ + public function test_context_param() { + // Collection. + $request = new WP_REST_Request( 'OPTIONS', '/__experimental/menu-locations' ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $this->assertEquals( 'view', $data['endpoints'][0]['args']['context']['default'] ); + $this->assertEquals( array( 'view', 'embed', 'edit' ), $data['endpoints'][0]['args']['context']['enum'] ); + $menu = 'primary'; + $this->register_nav_menu_locations( array( $menu ) ); + $request = new WP_REST_Request( 'OPTIONS', '/__experimental/menu-locations/' . $menu ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $this->assertEquals( 'view', $data['endpoints'][0]['args']['context']['default'] ); + $this->assertEquals( array( 'view', 'embed', 'edit' ), $data['endpoints'][0]['args']['context']['enum'] ); + } + + /** + * + */ + public function test_get_items() { + $menus = array( 'primary', 'secondary' ); + $this->register_nav_menu_locations( array( 'primary', 'secondary' ) ); + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'GET', '/__experimental/menu-locations' ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $data = array_values( $data ); + $this->assertCount( 2, $data ); + $names = wp_list_pluck( $data, 'name' ); + $descriptions = wp_list_pluck( $data, 'description' ); + $this->assertEquals( $menus, $names ); + $menu_descriptions = array_map( 'ucfirst', $names ); + $this->assertEquals( $menu_descriptions, $descriptions ); + } + + /** + * + */ + public function test_get_item() { + $menu = 'primary'; + $this->register_nav_menu_locations( array( $menu ) ); + + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'GET', '/__experimental/menu-locations/' . $menu ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $this->assertEquals( $menu, $data['name'] ); + } + + /** + * The test_create_item() method does not exist for menu locations. + */ + public function test_create_item() {} + + /** + * The test_update_item() method does not exist for menu locations. + */ + public function test_update_item() {} + + /** + * The test_delete_item() method does not exist for menu locations. + */ + public function test_delete_item() {} + + /** + * The test_prepare_item() method does not exist for menu locations. + */ + public function test_prepare_item() {} + + /** + * + */ + public function test_get_item_schema() { + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'OPTIONS', '/__experimental/menu-locations' ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $properties = $data['schema']['properties']; + $this->assertEquals( 3, count( $properties ) ); + $this->assertArrayHasKey( 'name', $properties ); + $this->assertArrayHasKey( 'description', $properties ); + $this->assertArrayHasKey( 'menu', $properties ); + } + + + /** + * + */ + public function test_get_item_menu_location_context_without_permission() { + wp_set_current_user( 0 ); + $request = new WP_REST_Request( 'GET', '/__experimental/menu-locations' ); + $response = rest_get_server()->dispatch( $request ); + + $this->assertErrorResponse( 'rest_cannot_view', $response, rest_authorization_required_code() ); + } + + /** + * + */ + public function test_get_items_menu_location_context_without_permission() { + $menu = 'primary'; + $this->register_nav_menu_locations( array( $menu ) ); + + wp_set_current_user( 0 ); + $request = new WP_REST_Request( 'GET', '/__experimental/menu-locations/' . $menu ); + $response = rest_get_server()->dispatch( $request ); + + $this->assertErrorResponse( 'rest_cannot_view', $response, rest_authorization_required_code() ); + } +} diff --git a/phpunit/class-rest-nav-menus-controller-test.php b/phpunit/class-rest-nav-menus-controller-test.php new file mode 100644 index 00000000000000..0ccbca208ef75d --- /dev/null +++ b/phpunit/class-rest-nav-menus-controller-test.php @@ -0,0 +1,554 @@ +user->create( + array( + 'role' => 'administrator', + ) + ); + self::$subscriber_id = $factory->user->create( + array( + 'role' => 'subscriber', + ) + ); + } + + /** + * + */ + public function setUp() { + parent::setUp(); + // Unregister all nav menu locations. + foreach ( array_keys( get_registered_nav_menus() ) as $location ) { + unregister_nav_menu( $location ); + } + + $orig_args = array( + 'name' => 'Original Name', + 'description' => 'Original Description', + 'slug' => 'original-slug', + 'taxonomy' => 'nav_menu', + ); + + $this->menu_id = $this->factory->term->create( $orig_args ); + + register_meta( + 'term', + 'test_single_menu', + array( + 'object_subtype' => self::TAXONOMY, + 'show_in_rest' => true, + 'single' => true, + 'type' => 'string', + ) + ); + } + + /** + * Register nav menu locations. + * + * @param array $locations Location slugs. + */ + public function register_nav_menu_locations( $locations ) { + foreach ( $locations as $location ) { + register_nav_menu( $location, ucfirst( $location ) ); + } + } + + /** + * + */ + public function test_register_routes() { + $routes = rest_get_server()->get_routes(); + $this->assertArrayHasKey( '/__experimental/menus', $routes ); + $this->assertArrayHasKey( '/__experimental/menus/(?P[\d]+)', $routes ); + } + + /** + * + */ + public function test_context_param() { + // Collection. + $request = new WP_REST_Request( 'OPTIONS', '/__experimental/menus' ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $this->assertEquals( 'view', $data['endpoints'][0]['args']['context']['default'] ); + $this->assertEqualSets( array( 'view', 'embed', 'edit' ), $data['endpoints'][0]['args']['context']['enum'] ); + // Single. + $tag1 = $this->factory->tag->create( array( 'name' => 'Season 5' ) ); + $request = new WP_REST_Request( 'OPTIONS', '/__experimental/menus/' . $tag1 ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $this->assertEquals( 'view', $data['endpoints'][0]['args']['context']['default'] ); + $this->assertEqualSets( array( 'view', 'embed', 'edit' ), $data['endpoints'][0]['args']['context']['enum'] ); + } + + /** + * + */ + public function test_registered_query_params() { + $request = new WP_REST_Request( 'OPTIONS', '/__experimental/menus' ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $keys = array_keys( $data['endpoints'][0]['args'] ); + sort( $keys ); + $this->assertEquals( + array( + 'context', + 'exclude', + 'hide_empty', + 'include', + 'offset', + 'order', + 'orderby', + 'page', + 'per_page', + 'post', + 'search', + 'slug', + ), + $keys + ); + } + + /** + * + */ + public function test_get_items() { + wp_set_current_user( self::$admin_id ); + wp_update_nav_menu_object( + 0, + array( + 'description' => 'Test get', + 'menu-name' => 'test Name get', + ) + ); + $request = new WP_REST_Request( 'GET', '/__experimental/menus' ); + $request->set_param( 'per_page', self::$per_page ); + $response = rest_get_server()->dispatch( $request ); + $this->check_get_taxonomy_terms_response( $response ); + } + + /** + * + */ + public function test_get_item() { + wp_set_current_user( self::$admin_id ); + $nav_menu_id = wp_update_nav_menu_object( + 0, + array( + 'description' => 'Test menu', + 'menu-name' => 'test Name', + ) + ); + $request = new WP_REST_Request( 'GET', '/__experimental/menus/' . $nav_menu_id ); + $response = rest_get_server()->dispatch( $request ); + $this->check_get_taxonomy_term_response( $response, $nav_menu_id ); + } + + /** + * + */ + public function test_create_item() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/__experimental/menus' ); + $request->set_param( 'name', 'My Awesome menus' ); + $request->set_param( 'description', 'This menu is so awesome.' ); + $response = rest_get_server()->dispatch( $request ); + $this->assertEquals( 201, $response->get_status() ); + $headers = $response->get_headers(); + $data = $response->get_data(); + $this->assertContains( '/__experimental/menus/' . $data['id'], $headers['Location'] ); + $this->assertEquals( 'My Awesome menus', $data['name'] ); + $this->assertEquals( 'This menu is so awesome.', $data['description'] ); + $this->assertEquals( 'my-awesome-menus', $data['slug'] ); + } + + /** + * + */ + public function test_update_item() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/__experimental/menus/' . $this->menu_id ); + $request->set_param( 'name', 'New Name' ); + $request->set_param( 'description', 'New Description' ); + $request->set_param( + 'meta', + array( + 'test_single_menu' => 'just meta', + ) + ); + $response = rest_get_server()->dispatch( $request ); + $this->assertEquals( 200, $response->get_status() ); + $data = $response->get_data(); + $this->assertEquals( 'New Name', $data['name'] ); + $this->assertEquals( 'New Description', $data['description'] ); + $this->assertEquals( 'new-name', $data['slug'] ); + $this->assertEquals( 'just meta', $data['meta']['test_single_menu'] ); + $this->assertFalse( isset( $data['meta']['test_cat_meta'] ) ); + } + + /** + * + */ + public function test_delete_item() { + wp_set_current_user( self::$admin_id ); + + $nav_menu_id = wp_update_nav_menu_object( + 0, + array( + 'description' => 'Deleted Menu', + 'menu-name' => 'Deleted Menu', + ) + ); + + $term = get_term_by( 'id', $nav_menu_id, self::TAXONOMY ); + + $request = new WP_REST_Request( 'DELETE', '/__experimental/menus/' . $term->term_id ); + $request->set_param( 'force', true ); + $response = rest_get_server()->dispatch( $request ); + $this->assertEquals( 200, $response->get_status() ); + $data = $response->get_data(); + $this->assertTrue( $data['deleted'] ); + $this->assertEquals( 'Deleted Menu', $data['previous']['name'] ); + } + + /** + * + */ + public function test_prepare_item() { + $nav_menu_id = wp_update_nav_menu_object( + 0, + array( + 'description' => 'Foo Menu', + 'menu-name' => 'Foo Menu', + ) + ); + + $term = get_term_by( 'id', $nav_menu_id, self::TAXONOMY ); + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'GET', '/__experimental/menus/' . $term->term_id ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->check_taxonomy_term( $term, $data, $response->get_links() ); + } + + /** + * + */ + public function test_get_item_schema() { + $request = new WP_REST_Request( 'OPTIONS', '/__experimental/menus' ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + $properties = $data['schema']['properties']; + $this->assertEquals( 6, count( $properties ) ); + $this->assertArrayHasKey( 'id', $properties ); + $this->assertArrayHasKey( 'description', $properties ); + $this->assertArrayHasKey( 'meta', $properties ); + $this->assertArrayHasKey( 'name', $properties ); + $this->assertArrayHasKey( 'slug', $properties ); + $this->assertArrayHasKey( 'locations', $properties ); + } + + /** + * + */ + public function test_create_item_with_location_permission_correct() { + $this->register_nav_menu_locations( array( 'primary', 'secondary' ) ); + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'POST', '/__experimental/menus' ); + $request->set_param( 'name', 'My Awesome Term' ); + $request->set_param( 'slug', 'so-awesome' ); + $request->set_param( 'locations', 'primary' ); + $response = rest_get_server()->dispatch( $request ); + $this->assertEquals( 201, $response->get_status() ); + $data = $response->get_data(); + $term_id = $data['id']; + $locations = get_nav_menu_locations(); + $this->assertEquals( $locations['primary'], $term_id ); + } + + /** + * + */ + public function test_create_item_with_location_permission_incorrect() { + wp_set_current_user( self::$subscriber_id ); + $request = new WP_REST_Request( 'POST', '/__experimental/menus' ); + $request->set_param( 'name', 'My Awesome Term' ); + $request->set_param( 'slug', 'so-awesome' ); + $request->set_param( 'locations', 'primary' ); + $response = rest_get_server()->dispatch( $request ); + $this->assertEquals( rest_authorization_required_code(), $response->get_status() ); + $this->assertErrorResponse( 'rest_cannot_assign_location', $response, rest_authorization_required_code() ); + } + + /** + * + */ + public function test_create_item_with_location_permission_no_location() { + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'POST', '/__experimental/menus' ); + $request->set_param( 'name', 'My Awesome Term' ); + $request->set_param( 'slug', 'so-awesome' ); + $request->set_param( 'locations', 'bar' ); + $response = rest_get_server()->dispatch( $request ); + $this->assertEquals( 400, $response->get_status() ); + $this->assertErrorResponse( 'rest_menu_location_invalid', $response, 400 ); + } + + /** + * + */ + public function test_update_item_with_no_location() { + $this->register_nav_menu_locations( array( 'primary', 'secondary' ) ); + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/__experimental/menus/' . $this->menu_id ); + $request->set_param( 'name', 'New Name' ); + $request->set_param( 'description', 'New Description' ); + $request->set_param( 'slug', 'new-slug' ); + $request->set_param( 'locations', 'bar' ); + $response = rest_get_server()->dispatch( $request ); + $this->assertEquals( 400, $response->get_status() ); + } + + /** + * + */ + public function test_update_item_with_location_permission_correct() { + $this->register_nav_menu_locations( array( 'primary', 'secondary' ) ); + wp_set_current_user( self::$admin_id ); + $request = new WP_REST_Request( 'POST', '/__experimental/menus/' . $this->menu_id ); + $request->set_param( 'name', 'New Name' ); + $request->set_param( 'description', 'New Description' ); + $request->set_param( 'slug', 'new-slug' ); + $request->set_param( 'locations', 'primary' ); + $response = rest_get_server()->dispatch( $request ); + $this->assertEquals( 200, $response->get_status() ); + $locations = get_nav_menu_locations(); + $this->assertEquals( $locations['primary'], $this->menu_id ); + } + + /** + * + */ + public function test_update_item_with_location_permission_incorrect() { + $this->register_nav_menu_locations( array( 'primary', 'secondary' ) ); + wp_set_current_user( self::$subscriber_id ); + $request = new WP_REST_Request( 'POST', '/__experimental/menus/' . $this->menu_id ); + $request->set_param( 'name', 'New Name' ); + $request->set_param( 'description', 'New Description' ); + $request->set_param( 'slug', 'new-slug' ); + $request->set_param( 'locations', 'primary' ); + $response = rest_get_server()->dispatch( $request ); + $this->assertEquals( rest_authorization_required_code(), $response->get_status() ); + } + + /** + * + */ + public function test_get_item_links() { + wp_set_current_user( self::$admin_id ); + + $nav_menu_id = wp_update_nav_menu_object( + 0, + array( + 'description' => 'Foo Menu', + 'menu-name' => 'Foo Menu', + ) + ); + + register_nav_menu( 'foo', 'Bar' ); + + set_theme_mod( 'nav_menu_locations', array( 'foo' => $nav_menu_id ) ); + + $request = new WP_REST_Request( 'GET', sprintf( '/__experimental/menus/%d', $nav_menu_id ) ); + $response = rest_get_server()->dispatch( $request ); + + $links = $response->get_links(); + $this->assertArrayHasKey( 'https://api.w.org/menu-location', $links ); + + $location_url = rest_url( '/__experimental/menu-locations/foo' ); + $this->assertEquals( $location_url, $links['https://api.w.org/menu-location'][0]['href'] ); + } + + /** + * + */ + public function test_change_menu_location() { + $this->register_nav_menu_locations( array( 'primary', 'secondary' ) ); + $secondary_id = self::factory()->term->create( + array( + 'name' => 'Secondary Name', + 'description' => 'Secondary Description', + 'slug' => 'secondary-slug', + 'taxonomy' => 'nav_menu', + ) + ); + + $locations = get_nav_menu_locations(); + $locations['primary'] = $this->menu_id; + $locations['secondary'] = $secondary_id; + set_theme_mod( 'nav_menu_locations', $locations ); + + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/__experimental/menus/' . $this->menu_id ); + $request->set_body_params( + array( + 'locations' => array( 'secondary' ), + ) + ); + $response = rest_get_server()->dispatch( $request ); + + $this->assertEquals( 200, $response->get_status() ); + + $locations = get_nav_menu_locations(); + $this->assertArrayNotHasKey( 'primary', $locations ); + $this->assertArrayHasKey( 'secondary', $locations ); + $this->assertEquals( $this->menu_id, $locations['secondary'] ); + } + + /** + * + */ + public function test_get_items_no_permission() { + wp_set_current_user( 0 ); + $request = new WP_REST_Request( 'GET', '/__experimental/menus' ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_cannot_view', $response, 401 ); + } + + /** + * + */ + public function test_get_item_no_permission() { + wp_set_current_user( 0 ); + $request = new WP_REST_Request( 'GET', '/__experimental/menus/' . $this->menu_id ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_cannot_view', $response, 401 ); + } + + /** + * + */ + public function test_get_items_wrong_permission() { + wp_set_current_user( self::$subscriber_id ); + $request = new WP_REST_Request( 'GET', '/__experimental/menus' ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_cannot_view', $response, 403 ); + } + + /** + * + */ + public function test_get_item_wrong_permission() { + wp_set_current_user( self::$subscriber_id ); + $request = new WP_REST_Request( 'GET', '/__experimental/menus/' . $this->menu_id ); + $response = rest_get_server()->dispatch( $request ); + $this->assertErrorResponse( 'rest_cannot_view', $response, 403 ); + } + + /** + * @param WP_REST_Response $response Response Class. + */ + protected function check_get_taxonomy_terms_response( $response ) { + $this->assertEquals( 200, $response->get_status() ); + $data = $response->get_data(); + $args = array( + 'hide_empty' => false, + ); + $tags = get_terms( self::TAXONOMY, $args ); + $this->assertEquals( count( $tags ), count( $data ) ); + $this->assertEquals( $tags[0]->term_id, $data[0]['id'] ); + $this->assertEquals( $tags[0]->name, $data[0]['name'] ); + $this->assertEquals( $tags[0]->slug, $data[0]['slug'] ); + $this->assertEquals( $tags[0]->description, $data[0]['description'] ); + } + + /** + * @param WP_REST_Response $response Response Class. + * @param int $id Term ID. + */ + protected function check_get_taxonomy_term_response( $response, $id ) { + $this->assertEquals( 200, $response->get_status() ); + + $data = $response->get_data(); + $menu = get_term( $id, self::TAXONOMY ); + $this->check_taxonomy_term( $menu, $data, $response->get_links() ); + } + + /** + * @param WP_Term $term WP_Term object. + * @param array $data Data from REST API. + * @param array $links Array of links. + */ + protected function check_taxonomy_term( $term, $data, $links ) { + $this->assertEquals( $term->term_id, $data['id'] ); + $this->assertEquals( $term->name, $data['name'] ); + $this->assertEquals( $term->slug, $data['slug'] ); + $this->assertEquals( $term->description, $data['description'] ); + $this->assertFalse( isset( $data['parent'] ) ); + + $relations = array( + 'self', + 'collection', + 'about', + 'https://api.w.org/post_type', + ); + + if ( ! empty( $data['parent'] ) ) { + $relations[] = 'up'; + } + + $this->assertEqualSets( $relations, array_keys( $links ) ); + $this->assertContains( 'wp/v2/taxonomies/' . $term->taxonomy, $links['about'][0]['href'] ); + $this->assertEquals( add_query_arg( 'menus', $term->term_id, rest_url( 'wp/v2/menu-items' ) ), $links['https://api.w.org/post_type'][0]['href'] ); + } + +}