Completed
Push — subscriber-api-endpoint ( 37b7d9 )
by
unknown
06:52
created

WPCOM_REST_API_V2_Endpoint_Subscribers   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

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

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