Completed
Push — fix/product-review-comment-end... ( fcd4b9...b9b2bf )
by Justin
174:21 queued 168:12
created

WPCOM_REST_API_V2_Endpoint_Subscribers   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 15.91 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
dl 7
loc 44
rs 10
c 0
b 0
f 0
wmc 5
lcom 0
cbo 1

4 Methods

Rating   Name   Duplication   Size   Complexity  
A register_routes() 0 10 1
A readable_permission_check() 0 7 2
A get_subscriber_count() 0 9 1
A __construct() 7 7 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * Subscribers: Get subscriber count
5
 *
6
 * @since 6.9
7
 */
8
class WPCOM_REST_API_V2_Endpoint_Subscribers extends WP_REST_Controller {
9 View Code Duplication
	function __construct() {
10
		$this->namespace = 'wpcom/v2';
11
		$this->rest_base = 'subscribers';
12
		// This endpoint *does not* need to connect directly to Jetpack sites.
13
		$this->wpcom_is_wpcom_only_endpoint = true;
14
		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
15
	}
16
17
	public function register_routes() {
18
		// GET /sites/<blog_id>/subscribers/count - Return number of subscribers for this site.
19
		register_rest_route( $this->namespace, '/' . $this->rest_base  . '/count', array(
20
			array(
21
				'methods'             => WP_REST_Server::READABLE,
22
				'callback'            => array( $this, 'get_subscriber_count' ),
23
				'permission_callback' => array( $this, 'readable_permission_check' ),
24
			)
25
		) );
26
	}
27
28
	public function readable_permission_check() {
29
		if ( ! current_user_can_for_blog( get_current_blog_id(), 'edit_posts' ) ) {
30
			return new WP_Error( 'authorization_required', 'Only users with the permission to edit posts can see the subscriber count.', array( 'status' => 401 ) );
31
		}
32
33
		return true;
34
	}
35
36
	/**
37
	 * Retrieves subscriber count
38
	 *
39
	 * @param WP_REST_Request $request incoming API request info
40
	 * @return array data object containing subscriber count
41
	 */
42
	public function get_subscriber_count( $request ) {
43
		$subscriptions = new Jetpack_Subscriptions_Widget();
44
		$subscriber_info = $subscriptions->fetch_subscriber_count();
45
		$subscriber_count = $subscriber_info['value'];
46
47
		return array(
48
			'count' => $subscriber_count
49
		);
50
	}
51
}
52
53
if ( Jetpack::is_module_active( 'subscriptions ') || ( defined( 'TESTING_IN_JETPACK' ) && TESTING_IN_JETPACK ) ) {
54
	wpcom_rest_api_v2_load_plugin( 'WPCOM_REST_API_V2_Endpoint_Subscribers' );
55
}
56