Query.php
84 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\MultiFormGoals\ProgressBar; |
| 4 | |
| 5 | use wpdb; |
| 6 | |
| 7 | /** |
| 8 | * Get the Total, Count, and Average of the payment totals for published donations of a given set of forms. |
| 9 | */ |
| 10 | class Query |
| 11 | { |
| 12 | |
| 13 | /** @var array */ |
| 14 | protected $formIDs; |
| 15 | |
| 16 | /** |
| 17 | * @var wpdb |
| 18 | */ |
| 19 | protected $wpdb; |
| 20 | |
| 21 | /** |
| 22 | * @var array $formIDs |
| 23 | */ |
| 24 | public function __construct($formIDs) |
| 25 | { |
| 26 | global $wpdb; |
| 27 | $this->wpdb = $wpdb; |
| 28 | $this->formIDs = $formIDs; |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * @since 3.14.0 Consider the donation mode (test or live) instead of querying both modes together |
| 33 | * @return string |
| 34 | */ |
| 35 | public function getSQL() |
| 36 | { |
| 37 | global $wpdb; |
| 38 | $mode = give_is_test_mode() ? 'test' : 'live'; |
| 39 | $sql = " |
| 40 | SELECT |
| 41 | sum( revenue.amount ) as total, |
| 42 | count( payment.ID ) as count |
| 43 | FROM {$wpdb->posts} as payment |
| 44 | JOIN {$wpdb->give_revenue} as revenue |
| 45 | ON revenue.donation_id = payment.ID |
| 46 | JOIN {$wpdb->paymentmeta} paymentMode |
| 47 | ON payment.ID = paymentMode.donation_id AND paymentMode.meta_key = '_give_payment_mode' |
| 48 | WHERE |
| 49 | payment.post_type = 'give_payment' |
| 50 | AND |
| 51 | payment.post_status IN ( 'publish', 'give_subscription' ) |
| 52 | AND |
| 53 | paymentMode.meta_value = '{$mode}' |
| 54 | "; |
| 55 | |
| 56 | if ( ! empty($this->formIDs)) { |
| 57 | $sql .= ' |
| 58 | AND |
| 59 | revenue.form_id IN ( ' . $this->getFormsString() . ' ) |
| 60 | '; |
| 61 | } |
| 62 | |
| 63 | return $sql; |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * @return string |
| 68 | */ |
| 69 | protected function getFormsString() |
| 70 | { |
| 71 | return implode(',', $this->formIDs); |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * @return stdClass |
| 76 | */ |
| 77 | public function getResults() |
| 78 | { |
| 79 | $sql = $this->getSQL(); |
| 80 | |
| 81 | return $this->wpdb->get_row($sql); |
| 82 | } |
| 83 | } |
| 84 |