From 4f3d93ef33bd05201e7ca2bb8c5e006cb75ecd29 Mon Sep 17 00:00:00 2001 From: Jonny Harris Date: Fri, 17 Sep 2021 06:33:07 +0100 Subject: [PATCH] Navigation Screen: Fix 'menu_exists' response status code (#34888) --- lib/class-wp-rest-menus-controller.php | 12 +++++----- .../class-rest-nav-menus-controller-test.php | 22 +++++++++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/lib/class-wp-rest-menus-controller.php b/lib/class-wp-rest-menus-controller.php index faee8714180543..c5a5e03b3fc773 100644 --- a/lib/class-wp-rest-menus-controller.php +++ b/lib/class-wp-rest-menus-controller.php @@ -352,16 +352,18 @@ public function create_item( $request ) { * 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' ); + + if ( in_array( 'menu_exists', $term->get_error_codes(), true ) ) { + $existing_term = get_term_by( 'name', $prepared_term['menu-name'], $this->taxonomy ); + $term->add_data( $existing_term->term_id, 'menu_exists' ); $term->add_data( array( 'status' => 400, - 'term_id' => $term_id, + 'term_id' => $existing_term->term_id, ) ); + } else { + $term->add_data( array( 'status' => 400 ) ); } return $term; diff --git a/phpunit/class-rest-nav-menus-controller-test.php b/phpunit/class-rest-nav-menus-controller-test.php index 6e71fbb1f93929..67cd59506d5d0f 100644 --- a/phpunit/class-rest-nav-menus-controller-test.php +++ b/phpunit/class-rest-nav-menus-controller-test.php @@ -221,6 +221,28 @@ public function test_create_item() { $this->assertEquals( 'my-awesome-menus', $data['slug'] ); } + /** + * + */ + public function test_create_item_same_name() { + wp_set_current_user( self::$admin_id ); + + wp_update_nav_menu_object( + 0, + array( + 'description' => 'This menu is so Original', + 'menu-name' => 'Original', + ) + ); + + $request = new WP_REST_Request( 'POST', '/__experimental/menus' ); + $request->set_param( 'name', 'Original' ); + $request->set_param( 'description', 'This menu is so Original' ); + $response = rest_get_server()->dispatch( $request ); + + $this->assertErrorResponse( 'menu_exists', $response, 400 ); + } + /** * */