REST API: Fix changing parameters with `set_param()` for some requests.

Prior to this commit, `WP_Rest_Request::get_param()` traversed through the parameter order but `WP_Rest_Request::set_param()` did not. For JSON requests (and likely other situations as well), this meant that changing a parameter with `set_param()` would have no effect on `get_param()`.

Props TimothyBlynJacobs.
Fixes #40344.



git-svn-id: https://develop.svn.wordpress.org/trunk@40815 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
James Nylen 2017-05-22 16:15:25 +00:00
parent 255bd917f2
commit 5ea3c91d57
2 changed files with 34 additions and 10 deletions

View File

@ -354,7 +354,11 @@ class WP_REST_Request implements ArrayAccess {
*/
protected function get_parameter_order() {
$order = array();
$content_type = $this->get_content_type();
if ( $content_type['value'] === 'application/json' ) {
$order[] = 'JSON';
}
$this->parse_json_params();
@ -424,15 +428,8 @@ class WP_REST_Request implements ArrayAccess {
* @param mixed $value Parameter value.
*/
public function set_param( $key, $value ) {
switch ( $this->method ) {
case 'POST':
$this->params['POST'][ $key ] = $value;
break;
default:
$this->params['GET'][ $key ] = $value;
break;
}
$order = $this->get_parameter_order();
$this->params[ $order[0] ][ $key ] = $value;
}
/**

View File

@ -580,4 +580,31 @@ class Tests_REST_Request extends WP_UnitTestCase {
$request = WP_REST_Request::from_url( $using_home );
$this->assertFalse( $request );
}
public function test_set_param() {
$request = new WP_REST_Request();
$request->set_param( 'param', 'value' );
$this->assertEquals( 'value', $request->get_param( 'param' ) );
}
public function test_set_param_follows_parameter_order() {
$request = new WP_REST_Request();
$request->add_header( 'content-type', 'application/json' );
$request->set_method( 'POST' );
$request->set_body( wp_json_encode( array(
'param' => 'value'
) ) );
$this->assertEquals( 'value', $request->get_param( 'param' ) );
$this->assertEquals(
array( 'param' => 'value' ),
$request->get_json_params()
);
$request->set_param( 'param', 'new_value' );
$this->assertEquals( 'new_value', $request->get_param( 'param' ) );
$this->assertEquals(
array( 'param' => 'new_value' ),
$request->get_json_params()
);
}
}