Completed
Push — add/comment-counts-endpoint ( b9e596 )
by
unknown
09:07 queued 01:13
created

callback()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 31
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 15
nc 6
nop 2
dl 0
loc 31
rs 8.439
c 0
b 0
f 0
1
<?php
2
/*
3
 * WARNING: This file is distributed verbatim in Jetpack.
4
 * There should be nothing WordPress.com specific in this file.
5
 *
6
 * @hide-in-jetpack
7
 */
8
9
new WPCOM_JSON_API_GET_Comment_Counts_Endpoint( array(
10
	'description'   => 'Get comment counts for each available status',
11
	'group'         => 'comments',
12
	'stat'          => 'comments:1:comment-counts',
13
	'method'        => 'GET',
14
	'path'          => '/sites/%s/comment-counts',
15
	'path_labels'   => array(
16
		'$site'       => '(int|string) Site ID or domain',
17
	),
18
19
	'query_parameters' => array(
20
		'post_id' => '(int) post ID for filtering the comment counts by post',
21
	),
22
23
	'example_request' => 'https://public-api.wordpress.com/rest/v1/sites/en.blog.wordpress.com/comment-counts',
24
25
	'response_format' => array(
26
		'counts' => array(
27
			'approved' => '(int) Number of approved comments',
28
			'awaiting_moderation' => '(int) Number of unapproved comments',
29
			'trash' => '(int) Number of trash comments',
30
			'spam' => '(int) Number of spam comments',
31
			'post-trashed' => '(int) Number of comments whose parent post has been trashed',
32
			'total_comments' => '(int) Combined number of comments in each category',
33
			'all' => '(int) Combined number of approved and awaiting_moderation comments',
34
		)
35
	)
36
) );
37
38
class WPCOM_JSON_API_GET_Comment_Counts_Endpoint extends WPCOM_JSON_API_Endpoint {
39
40
	// /sites/%s/comment-counts
41
	public function callback( $path = '', $blog_id = 0 ) {
42
		$blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
43
44
		if ( is_wp_error( $blog_id ) ) {
45
			return $blog_id;
46
		}
47
48
		if ( ! get_current_user_id() ) {
49
			return new WP_Error( 'authorization_required', 'An active access token must be used to retrieve comment counts.', 403 );
50
		}
51
52
		if ( ! current_user_can_for_blog( $blog_id, 'moderate_comments' ) ) {
53
			return new WP_Error( 'authorization_required', 'You are not authorized to view comment counts for this blog.', 403 );
54
		}
55
56
		$args = $this->query_args();
57
58
		// If 0 is passed wp_count_comments will default to fetching counts for the whole site.
59
		$post_id = 0;
60
61
		if ( isset( $args['post_id'] ) ) {
62
			$post_id = intval( $args['post_id'] );
63
64
			// Check if post with given id exists.
65
			if ( ! is_object( get_post( $post_id ) ) ) {
66
				return new WP_Error( 'invalid_input', 'Provided post_id does not exist', 400 );
67
			}
68
		}
69
70
		return wp_count_comments( $post_id );
71
	}
72
}
73