Ticket #35803: 35803.3.diff
File 35803.3.diff, 3.0 KB (added by , 9 years ago) |
---|
-
src/wp-includes/rest-api/class-wp-rest-request.php
934 934 unset( $this->params[ $type ][ $offset ] ); 935 935 } 936 936 } 937 938 /** 939 * Gets a WP_REST_Request object from a full URL. 940 * 941 * @since 4.5.0 942 * 943 * @param string $url URL with protocol, domain, path and query args. 944 * @return WP_REST_Request|false WP_REST_Request object on success, false on failure. 945 */ 946 public static function from_url( $url ) { 947 $bits = parse_url( $url ); 948 $route = null; 949 $query_params = array(); 950 951 if ( ! empty( $bits['query'] ) ) { 952 wp_parse_str( $bits['query'], $query_params ); 953 } 954 955 if ( get_option( 'permalink_structure' ) ) { 956 $api_root = untrailingslashit( rest_url() ); 957 $api_url_part = substr( $url, strlen( $api_root ) ); 958 $parsed = parse_url( $api_url_part ); 959 if ( ! empty( $parsed['path'] ) ) { 960 $route = $parsed['path']; 961 } 962 } elseif ( ! empty( $query_params['rest_route'] ) ) { 963 $route = $query_params['rest_route']; 964 unset( $query_params['rest_route'] ); 965 } 966 967 $request = false; 968 if ( ! empty( $route ) ) { 969 $request = new WP_REST_Request( 'GET', $route ); 970 $request->set_query_params( $query_params ); 971 } 972 973 /** 974 * Filter the request generated from a URL. 975 * 976 * @param WP_REST_Request|false $request Generated request object, or false if URL could not be parsed. 977 * @param string $url URL the request was generated from. 978 */ 979 return apply_filters( 'rest_request_from_url', $request, $url ); 980 } 937 981 } -
tests/phpunit/tests/rest-api/rest-request.php
420 420 public function _return_wp_error_on_validate_callback() { 421 421 return new WP_Error( 'some-error', 'This is not valid!' ); 422 422 } 423 424 /** 425 * @dataProvider data_rest_request_from_url 426 */ 427 public function test_rest_request_from_url( $permalink_structure, $original_url ) { 428 update_option( 'permalink_structure', $permalink_structure ); 429 $url = add_query_arg( 'foo', 'bar', rest_url( '/wp/v2/posts/1' ) ); 430 $this->assertEquals( $original_url, $url ); 431 $request = WP_REST_Request::from_url( $url ); 432 $this->assertInstanceOf( 'WP_REST_Request', $request ); 433 $this->assertEquals( '/wp/v2/posts/1', $request->get_route() ); 434 $this->assertEqualSets( array( 435 'foo' => 'bar', 436 ), $request->get_query_params() ); 437 } 438 439 public function data_rest_request_from_url() { 440 return array( 441 array( 442 'permalink_structure' => '/%post_name%/', 443 'original_url' => 'http://' . WP_TESTS_DOMAIN . '/wp-json/wp/v2/posts/1?foo=bar', 444 ), 445 array( 446 'permalink_structure' => '', 447 'original_url' => 'http://' . WP_TESTS_DOMAIN . '/?rest_route=%2Fwp%2Fv2%2Fposts%2F1&foo=bar', 448 ), 449 ); 450 } 423 451 }