REST API: Allow shortcircuiting rest_pre_insert_comment

rest_pre_insert_{post_type} allows returning a WP_Error from the filter to shortcircuit actually creating the object, so it makes sense to do so for comments too.

Props dspilka.
Fixes #39578.


git-svn-id: https://develop.svn.wordpress.org/trunk@39922 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Ryan McCue 2017-01-17 05:17:15 +00:00
parent 16bbc492a5
commit bbf129c935
2 changed files with 33 additions and 1 deletions

View File

@ -552,13 +552,19 @@ class WP_REST_Comments_Controller extends WP_REST_Controller {
* Filters a comment before it is inserted via the REST API.
*
* Allows modification of the comment right before it is inserted via wp_insert_comment().
* Returning a WP_Error value from the filter will shortcircuit insertion and allow
* skipping further processing.
*
* @since 4.7.0
* @since 4.8.0 $prepared_comment can now be a WP_Error to shortcircuit insertion.
*
* @param array $prepared_comment The prepared comment data for wp_insert_comment().
* @param array|WP_Error $prepared_comment The prepared comment data for wp_insert_comment().
* @param WP_REST_Request $request Request used to insert the comment.
*/
$prepared_comment = apply_filters( 'rest_pre_insert_comment', $prepared_comment, $request );
if ( is_wp_error( $prepared_comment ) ) {
return $prepared_comment;
}
$comment_id = wp_insert_comment( wp_filter_comment( wp_slash( (array) $prepared_comment ) ) );

View File

@ -985,6 +985,32 @@ class WP_Test_REST_Comments_Controller extends WP_Test_REST_Controller_Testcase
$this->assertEquals( $params['content']['raw'], $new_comment->comment_content );
}
public function test_create_item_error_from_filter() {
add_filter( 'rest_pre_insert_comment', array( $this, 'return_premade_error' ) );
wp_set_current_user( self::$admin_id );
$params = array(
'post' => self::$post_id,
'author_name' => 'Homer Jay Simpson',
'author_email' => 'homer@example.org',
'content' => array(
'raw' => 'Aw, he loves beer. Here, little fella.'
),
);
$request = new WP_REST_Request( 'POST', '/wp/v2/comments' );
$request->add_header( 'content-type', 'application/json' );
$request->set_body( wp_json_encode( $params ) );
$response = $this->server->dispatch( $request );
$this->assertErrorResponse( 'test_rest_premade_error', $response, 418 );
}
public function return_premade_error() {
return new WP_Error( 'test_rest_premade_error', "I'm sorry, I thought he was a party robot.", array( 'status' => 418 ) );
}
public function test_create_comment_missing_required_author_name() {
add_filter( 'rest_allow_anonymous_comments', '__return_true' );
update_option( 'require_name_email', 1 );