Completed
Push — mailchimp/introduce-shortcode ( b80f24...10eaea )
by
unknown
07:06
created

WPCOM_REST_API_V2_Endpoint_Subscribers   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 2
dl 0
loc 48
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A register_routes() 0 10 1
A readable_permission_check() 0 7 2
A get_subscriber_count() 0 13 2
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
	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
		// Get the most up to date subscriber count when request is not a test
44
		if ( ! Jetpack_Constants::is_defined( 'TESTING_IN_JETPACK' ) ) {
45
			delete_transient( 'wpcom_subscribers_total' );
46
		}
47
48
		$subscriber_info = Jetpack_Subscriptions_Widget::fetch_subscriber_count();
49
		$subscriber_count = $subscriber_info['value'];
50
51
		return array(
52
			'count' => $subscriber_count
53
		);
54
	}
55
}
56
57
if (
58
	Jetpack::is_module_active( 'subscriptions' ) ||
59
	( Jetpack_Constants::is_defined( 'TESTING_IN_JETPACK' ) && Jetpack_Constants::get_constant( 'TESTING_IN_JETPACK' ) )
60
) {
61
	wpcom_rest_api_v2_load_plugin( 'WPCOM_REST_API_V2_Endpoint_Subscribers' );
62
}
63