PluginProbe
GiveWP – Donation Plugin and Fundraising Platform / 4.16.8.1
GiveWP – Donation Plugin and Fundraising Platform v4.16.8.1
4.16.9 4.16.8.1 4.16.8 4.16.7.2 4.16.7.1 4.16.7 4.16.6.1 4.16.6 4.16.5.1 4.16.5 4.16.4 4.16.3 4.16.2 4.16.1 4.16.0 4.15.5 4.15.4 4.15.3 4.15.2 4.15.1 4.15.0 2.3.0 2.3.1 2.3.2 2.30.0 All 255 releases
give / src / Donors / Endpoints / ListDonorsStats.php

ListDonorsStats.php in GiveWP – Donation Plugin and Fundraising Platform 4.16.8.1, at src/Donors/Endpoints/ListDonorsStats.php

90 lines 2.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Give\Donors\Endpoints;
4
5 use Give\Framework\Database\DB;
6 use WP_REST_Request;
7 use WP_REST_Response;
8
9 /**
10 * @since 4.11.0
11 */
12 class ListDonorsStats extends Endpoint
13 {
14 /**
15 * @var string
16 */
17 protected $endpoint = 'admin/donors/stats';
18
19 /**
20 * @var WP_REST_Request
21 */
22 protected $request;
23
24 /**
25 * @since 4.11.0
26 */
27 public function registerRoute()
28 {
29 register_rest_route(
30 'give-api/v2',
31 $this->endpoint,
32 [
33 [
34 'methods' => 'GET',
35 'callback' => [$this, 'handleRequest'],
36 'permission_callback' => [$this, 'permissionsCheck'],
37 ],
38 'args' => [
39 ],
40 ]
41 );
42 }
43
44 /**
45 * @since 4.11.0
46 */
47 public function handleRequest(WP_REST_Request $request): WP_REST_Response
48 {
49 $this->request = $request;
50
51 $statistics = $this->getDonorStatistics();
52
53 return new WP_REST_Response($statistics);
54 }
55
56 /**
57 * Get all donor statistics in a single optimized query
58 *
59 * @since 4.11.0
60 */
61 public function getDonorStatistics(): array
62 {
63 $query = DB::table('give_donors', 'donors')
64 ->leftJoin('give_subscriptions as subscriptions', 'donors.id', 'subscriptions.customer_id')
65 ->selectRaw('SELECT
66 COUNT(DISTINCT donors.id) as total_donors,
67 COUNT(DISTINCT subscriptions.customer_id) as recurring_donors,
68 COUNT(DISTINCT donors.id) - COUNT(DISTINCT subscriptions.customer_id) as one_time_donors
69 ');
70
71 $result = $query->get();
72
73 // Handle case when no results are found
74 if (!$result) {
75 return [
76 'donorsCount' => 0,
77 'oneTimeDonorsCount' => 0,
78 'subscribersCount' => 0,
79 ];
80 }
81
82 return [
83 'donorsCount' => (int) $result->total_donors,
84 'oneTimeDonorsCount' => (int) $result->one_time_donors,
85 'subscribersCount' => (int) $result->recurring_donors,
86 ];
87 }
88
89 }
90