Passed
Push — master ( 9d88bf...b642cd )
by Brian
15:13
created
includes/wpinv-helper-functions.php 1 patch
Spacing   +286 added lines, -286 removed lines patch added patch discarded remove patch
@@ -6,7 +6,7 @@  discard block
 block discarded – undo
6 6
  * @package Invoicing
7 7
  */
8 8
 
9
-defined( 'ABSPATH' ) || exit;
9
+defined('ABSPATH') || exit;
10 10
 
11 11
 /**
12 12
  * Are we supporting item quantities?
@@ -20,35 +20,35 @@  discard block
 block discarded – undo
20 20
  */
21 21
 function wpinv_get_ip() {
22 22
 
23
-    if ( isset( $_SERVER['HTTP_X_REAL_IP'] ) ) {
24
-        return sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_REAL_IP'] ) );
23
+    if (isset($_SERVER['HTTP_X_REAL_IP'])) {
24
+        return sanitize_text_field(wp_unslash($_SERVER['HTTP_X_REAL_IP']));
25 25
     }
26 26
 
27
-    if ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
27
+    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
28 28
         // Proxy servers can send through this header like this: X-Forwarded-For: client1, proxy1, proxy2
29 29
         // Make sure we always only send through the first IP in the list which should always be the client IP.
30
-        return (string) rest_is_ip_address( trim( current( preg_split( '/,/', sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ) ) ) );
30
+        return (string) rest_is_ip_address(trim(current(preg_split('/,/', sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR']))))));
31 31
     }
32 32
 
33
-    if ( isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {
34
-        return sanitize_text_field( wp_unslash( $_SERVER['HTTP_CLIENT_IP'] ) );
33
+    if (isset($_SERVER['HTTP_CLIENT_IP'])) {
34
+        return sanitize_text_field(wp_unslash($_SERVER['HTTP_CLIENT_IP']));
35 35
     }
36 36
 
37
-    if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
38
-        return sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
37
+    if (isset($_SERVER['REMOTE_ADDR'])) {
38
+        return sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR']));
39 39
     }
40 40
 
41 41
     return '';
42 42
 }
43 43
 
44 44
 function wpinv_get_user_agent() {
45
-    if ( ! empty( $_SERVER['HTTP_USER_AGENT'] ) ) {
46
-        $user_agent = sanitize_text_field( $_SERVER['HTTP_USER_AGENT'] );
45
+    if (!empty($_SERVER['HTTP_USER_AGENT'])) {
46
+        $user_agent = sanitize_text_field($_SERVER['HTTP_USER_AGENT']);
47 47
     } else {
48 48
         $user_agent = '';
49 49
     }
50 50
 
51
-    return apply_filters( 'wpinv_get_user_agent', $user_agent );
51
+    return apply_filters('wpinv_get_user_agent', $user_agent);
52 52
 }
53 53
 
54 54
 /**
@@ -57,16 +57,16 @@  discard block
 block discarded – undo
57 57
  * @param string $amount The amount to sanitize.
58 58
  * @return float
59 59
  */
60
-function getpaid_standardize_amount( $amount ) {
60
+function getpaid_standardize_amount($amount) {
61 61
 
62
-    $amount = str_replace( wpinv_thousands_separator(), '', $amount );
63
-    $amount = str_replace( wpinv_decimal_separator(), '.', $amount );
64
-    if ( is_numeric( $amount ) ) {
65
-        return floatval( $amount );
62
+    $amount = str_replace(wpinv_thousands_separator(), '', $amount);
63
+    $amount = str_replace(wpinv_decimal_separator(), '.', $amount);
64
+    if (is_numeric($amount)) {
65
+        return floatval($amount);
66 66
     }
67 67
 
68 68
     // Cast the remaining to a float.
69
-    return wpinv_round_amount( preg_replace( '/[^0-9\.\-]/', '', $amount ) );
69
+    return wpinv_round_amount(preg_replace('/[^0-9\.\-]/', '', $amount));
70 70
 
71 71
 }
72 72
 
@@ -75,8 +75,8 @@  discard block
 block discarded – undo
75 75
  *
76 76
  * @param string $amount The amount to sanitize.
77 77
  */
78
-function getpaid_unstandardize_amount( $amount ) {
79
-    return str_replace( '.', wpinv_decimal_separator(), $amount );
78
+function getpaid_unstandardize_amount($amount) {
79
+    return str_replace('.', wpinv_decimal_separator(), $amount);
80 80
 }
81 81
 
82 82
 /**
@@ -84,24 +84,24 @@  discard block
 block discarded – undo
84 84
  *
85 85
  * @param string $amount The amount to sanitize.
86 86
  */
87
-function wpinv_sanitize_amount( $amount ) {
87
+function wpinv_sanitize_amount($amount) {
88 88
 
89
-    if ( is_numeric( $amount ) ) {
90
-        return floatval( $amount );
89
+    if (is_numeric($amount)) {
90
+        return floatval($amount);
91 91
     }
92 92
 
93 93
     // Separate the decimals and thousands.
94
-    $amount    = empty( $amount ) ? '0' : (string) $amount;
95
-    $amount    = explode( wpinv_decimal_separator(), $amount );
94
+    $amount    = empty($amount) ? '0' : (string) $amount;
95
+    $amount    = explode(wpinv_decimal_separator(), $amount);
96 96
 
97 97
     // Remove thousands.
98
-    $amount[0] = str_replace( wpinv_thousands_separator(), '', $amount[0] );
98
+    $amount[0] = str_replace(wpinv_thousands_separator(), '', $amount[0]);
99 99
 
100 100
     // Convert back to string.
101
-    $amount = count( $amount ) > 1 ? "{$amount[0]}.{$amount[1]}" : $amount[0];
101
+    $amount = count($amount) > 1 ? "{$amount[0]}.{$amount[1]}" : $amount[0];
102 102
 
103 103
     // Cast the remaining to a float.
104
-    return (float) preg_replace( '/[^0-9\.\-]/', '', $amount );
104
+    return (float) preg_replace('/[^0-9\.\-]/', '', $amount);
105 105
 
106 106
 }
107 107
 
@@ -111,19 +111,19 @@  discard block
 block discarded – undo
111 111
  * @param float $amount
112 112
  * @param float|string|int|null $decimals
113 113
  */
114
-function wpinv_round_amount( $amount, $decimals = null, $use_sprintf = false ) {
114
+function wpinv_round_amount($amount, $decimals = null, $use_sprintf = false) {
115 115
 
116
-    if ( $decimals === null ) {
116
+    if ($decimals === null) {
117 117
         $decimals = wpinv_decimals();
118 118
     }
119 119
 
120
-    if ( $use_sprintf ) {
121
-        $amount = sprintf( "%.{$decimals}f", (float) $amount );
120
+    if ($use_sprintf) {
121
+        $amount = sprintf("%.{$decimals}f", (float) $amount);
122 122
     } else {
123
-        $amount = round( (float) $amount, absint( $decimals ) );
123
+        $amount = round((float) $amount, absint($decimals));
124 124
     }
125 125
 
126
-    return apply_filters( 'wpinv_round_amount', $amount, $decimals );
126
+    return apply_filters('wpinv_round_amount', $amount, $decimals);
127 127
 }
128 128
 
129 129
 /**
@@ -135,32 +135,32 @@  discard block
 block discarded – undo
135 135
  * @param string|WPInv_Invoice $invoice The invoice object|post type|type
136 136
  * @return array
137 137
  */
138
-function wpinv_get_invoice_statuses( $draft = false, $trashed = false, $invoice = false ) {
138
+function wpinv_get_invoice_statuses($draft = false, $trashed = false, $invoice = false) {
139 139
 
140 140
 	$invoice_statuses = array(
141
-		'wpi-pending'    => _x( 'Pending payment', 'Invoice status', 'invoicing' ),
142
-        'publish'        => _x( 'Paid', 'Invoice status', 'invoicing' ),
143
-        'wpi-processing' => _x( 'Processing', 'Invoice status', 'invoicing' ),
144
-		'wpi-onhold'     => _x( 'On hold', 'Invoice status', 'invoicing' ),
145
-		'wpi-cancelled'  => _x( 'Cancelled', 'Invoice status', 'invoicing' ),
146
-		'wpi-refunded'   => _x( 'Refunded', 'Invoice status', 'invoicing' ),
147
-        'wpi-failed'     => _x( 'Failed', 'Invoice status', 'invoicing' ),
148
-        'wpi-renewal'    => _x( 'Renewal Payment', 'Invoice status', 'invoicing' ),
141
+		'wpi-pending'    => _x('Pending payment', 'Invoice status', 'invoicing'),
142
+        'publish'        => _x('Paid', 'Invoice status', 'invoicing'),
143
+        'wpi-processing' => _x('Processing', 'Invoice status', 'invoicing'),
144
+		'wpi-onhold'     => _x('On hold', 'Invoice status', 'invoicing'),
145
+		'wpi-cancelled'  => _x('Cancelled', 'Invoice status', 'invoicing'),
146
+		'wpi-refunded'   => _x('Refunded', 'Invoice status', 'invoicing'),
147
+        'wpi-failed'     => _x('Failed', 'Invoice status', 'invoicing'),
148
+        'wpi-renewal'    => _x('Renewal Payment', 'Invoice status', 'invoicing'),
149 149
     );
150 150
 
151
-    if ( $draft ) {
152
-        $invoice_statuses['draft'] = __( 'Draft', 'invoicing' );
151
+    if ($draft) {
152
+        $invoice_statuses['draft'] = __('Draft', 'invoicing');
153 153
     }
154 154
 
155
-    if ( $trashed ) {
156
-        $invoice_statuses['trash'] = __( 'Trash', 'invoicing' );
155
+    if ($trashed) {
156
+        $invoice_statuses['trash'] = __('Trash', 'invoicing');
157 157
     }
158 158
 
159
-    if ( $invoice instanceof WPInv_Invoice ) {
159
+    if ($invoice instanceof WPInv_Invoice) {
160 160
         $invoice = $invoice->get_post_type();
161 161
     }
162 162
 
163
-	return apply_filters( 'wpinv_statuses', $invoice_statuses, $invoice );
163
+	return apply_filters('wpinv_statuses', $invoice_statuses, $invoice);
164 164
 }
165 165
 
166 166
 /**
@@ -169,11 +169,11 @@  discard block
 block discarded – undo
169 169
  * @param string $status The raw status
170 170
  * @param string|WPInv_Invoice $invoice The invoice object|post type|type
171 171
  */
172
-function wpinv_status_nicename( $status, $invoice = false ) {
173
-    $statuses = wpinv_get_invoice_statuses( true, true, $invoice );
174
-    $status   = isset( $statuses[ $status ] ) ? $statuses[ $status ] : $status;
172
+function wpinv_status_nicename($status, $invoice = false) {
173
+    $statuses = wpinv_get_invoice_statuses(true, true, $invoice);
174
+    $status   = isset($statuses[$status]) ? $statuses[$status] : $status;
175 175
 
176
-    return sanitize_text_field( $status );
176
+    return sanitize_text_field($status);
177 177
 }
178 178
 
179 179
 /**
@@ -181,13 +181,13 @@  discard block
 block discarded – undo
181 181
  *
182 182
  * @param string $current
183 183
  */
184
-function wpinv_get_currency( $current = '' ) {
184
+function wpinv_get_currency($current = '') {
185 185
 
186
-    if ( empty( $current ) ) {
187
-        $current = apply_filters( 'wpinv_currency', wpinv_get_option( 'currency', 'USD' ) );
186
+    if (empty($current)) {
187
+        $current = apply_filters('wpinv_currency', wpinv_get_option('currency', 'USD'));
188 188
     }
189 189
 
190
-    return trim( strtoupper( $current ) );
190
+    return trim(strtoupper($current));
191 191
 }
192 192
 
193 193
 /**
@@ -195,25 +195,25 @@  discard block
 block discarded – undo
195 195
  *
196 196
  * @param string|null $currency The currency code. Defaults to the default currency.
197 197
  */
198
-function wpinv_currency_symbol( $currency = null ) {
198
+function wpinv_currency_symbol($currency = null) {
199 199
 
200 200
     // Prepare the currency.
201
-    $currency = empty( $currency ) ? wpinv_get_currency() : wpinv_clean( $currency );
201
+    $currency = empty($currency) ? wpinv_get_currency() : wpinv_clean($currency);
202 202
 
203 203
     // Fetch all symbols.
204 204
     $symbols = wpinv_get_currency_symbols();
205 205
 
206 206
     // Fetch this currencies symbol.
207
-    $currency_symbol = isset( $symbols[ $currency ] ) ? $symbols[ $currency ] : $currency;
207
+    $currency_symbol = isset($symbols[$currency]) ? $symbols[$currency] : $currency;
208 208
 
209 209
     // Filter the symbol.
210
-    return apply_filters( 'wpinv_currency_symbol', $currency_symbol, $currency );
210
+    return apply_filters('wpinv_currency_symbol', $currency_symbol, $currency);
211 211
 }
212 212
 
213 213
 function wpinv_currency_position() {
214
-    $position = wpinv_get_option( 'currency_position', 'left' );
214
+    $position = wpinv_get_option('currency_position', 'left');
215 215
 
216
-    return apply_filters( 'wpinv_currency_position', $position );
216
+    return apply_filters('wpinv_currency_position', $position);
217 217
 }
218 218
 
219 219
 /**
@@ -221,13 +221,13 @@  discard block
 block discarded – undo
221 221
  *
222 222
  * @param $string|null $current
223 223
  */
224
-function wpinv_thousands_separator( $current = null ) {
224
+function wpinv_thousands_separator($current = null) {
225 225
 
226
-    if ( null == $current ) {
227
-        $current = wpinv_get_option( 'thousands_separator', ',' );
226
+    if (null == $current) {
227
+        $current = wpinv_get_option('thousands_separator', ',');
228 228
     }
229 229
 
230
-    return trim( $current );
230
+    return trim($current);
231 231
 }
232 232
 
233 233
 /**
@@ -235,13 +235,13 @@  discard block
 block discarded – undo
235 235
  *
236 236
  * @param $string|null $current
237 237
  */
238
-function wpinv_decimal_separator( $current = null ) {
238
+function wpinv_decimal_separator($current = null) {
239 239
 
240
-    if ( null == $current ) {
241
-        $current = wpinv_get_option( 'decimal_separator', '.' );
240
+    if (null == $current) {
241
+        $current = wpinv_get_option('decimal_separator', '.');
242 242
     }
243 243
 
244
-    return trim( $current );
244
+    return trim($current);
245 245
 }
246 246
 
247 247
 /**
@@ -249,27 +249,27 @@  discard block
 block discarded – undo
249 249
  *
250 250
  * @param $string|null $current
251 251
  */
252
-function wpinv_decimals( $current = null ) {
252
+function wpinv_decimals($current = null) {
253 253
 
254
-    if ( null == $current ) {
255
-        $current = wpinv_get_option( 'decimals', 2 );
254
+    if (null == $current) {
255
+        $current = wpinv_get_option('decimals', 2);
256 256
     }
257 257
 
258
-    return absint( $current );
258
+    return absint($current);
259 259
 }
260 260
 
261 261
 /**
262 262
  * Retrieves a list of all supported currencies.
263 263
  */
264 264
 function wpinv_get_currencies() {
265
-    return apply_filters( 'wpinv_currencies', wpinv_get_data( 'currencies' ) );
265
+    return apply_filters('wpinv_currencies', wpinv_get_data('currencies'));
266 266
 }
267 267
 
268 268
 /**
269 269
  * Retrieves a list of all currency symbols.
270 270
  */
271 271
 function wpinv_get_currency_symbols() {
272
-    return apply_filters( 'wpinv_currency_symbols', wpinv_get_data( 'currency-symbols' ) );
272
+    return apply_filters('wpinv_currency_symbols', wpinv_get_data('currency-symbols'));
273 273
 }
274 274
 
275 275
 /**
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
 	$currency_pos = wpinv_currency_position();
282 282
 	$format       = '%1$s%2$s';
283 283
 
284
-	switch ( $currency_pos ) {
284
+	switch ($currency_pos) {
285 285
 		case 'left':
286 286
 			$format = '%1$s%2$s';
287 287
 			break;
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
 			break;
297 297
 	}
298 298
 
299
-	return apply_filters( 'getpaid_price_format', $format, $currency_pos );
299
+	return apply_filters('getpaid_price_format', $format, $currency_pos);
300 300
 }
301 301
 
302 302
 /**
@@ -306,8 +306,8 @@  discard block
 block discarded – undo
306 306
  * @param  string $currency Currency.
307 307
  * @return string
308 308
  */
309
-function wpinv_the_price( $amount = 0, $currency = '' ) {
310
-    echo wp_kses_post( wpinv_price( $amount, $currency ) );
309
+function wpinv_the_price($amount = 0, $currency = '') {
310
+    echo wp_kses_post(wpinv_price($amount, $currency));
311 311
 }
312 312
 
313 313
 /**
@@ -317,25 +317,25 @@  discard block
 block discarded – undo
317 317
  * @param  string $currency Currency.
318 318
  * @return string
319 319
  */
320
-function wpinv_price( $amount = 0, $currency = '' ) {
320
+function wpinv_price($amount = 0, $currency = '') {
321 321
 
322 322
     // Backwards compatibility.
323
-    $amount             = wpinv_sanitize_amount( $amount );
323
+    $amount             = wpinv_sanitize_amount($amount);
324 324
 
325 325
     // Prepare variables.
326
-    $currency           = wpinv_get_currency( $currency );
326
+    $currency           = wpinv_get_currency($currency);
327 327
     $amount             = (float) $amount;
328 328
     $unformatted_amount = $amount;
329 329
     $negative           = $amount < 0;
330
-    $amount             = apply_filters( 'getpaid_raw_amount', floatval( $negative ? $amount * -1 : $amount ) );
331
-    $amount             = wpinv_format_amount( $amount );
330
+    $amount             = apply_filters('getpaid_raw_amount', floatval($negative ? $amount * -1 : $amount));
331
+    $amount             = wpinv_format_amount($amount);
332 332
 
333 333
     // Format the amount.
334 334
     $format             = getpaid_get_price_format();
335
-    $formatted_amount   = ( $negative ? '-' : '' ) . sprintf( $format, '<span class="getpaid-currency__symbol">' . wpinv_currency_symbol( $currency ) . '</span>', $amount );
335
+    $formatted_amount   = ($negative ? '-' : '') . sprintf($format, '<span class="getpaid-currency__symbol">' . wpinv_currency_symbol($currency) . '</span>', $amount);
336 336
 
337 337
     // Filter the formatting.
338
-    return apply_filters( 'wpinv_price', $formatted_amount, $amount, $currency, $unformatted_amount );
338
+    return apply_filters('wpinv_price', $formatted_amount, $amount, $currency, $unformatted_amount);
339 339
 }
340 340
 
341 341
 /**
@@ -346,25 +346,25 @@  discard block
 block discarded – undo
346 346
  * @param  bool     $calculate Whether or not to apply separators.
347 347
  * @return string
348 348
  */
349
-function wpinv_format_amount( $amount, $decimals = null, $calculate = false ) {
349
+function wpinv_format_amount($amount, $decimals = null, $calculate = false) {
350 350
     $thousands_sep = wpinv_thousands_separator();
351 351
     $decimal_sep   = wpinv_decimal_separator();
352
-    $decimals      = wpinv_decimals( $decimals );
353
-    $amount        = wpinv_sanitize_amount( $amount );
352
+    $decimals      = wpinv_decimals($decimals);
353
+    $amount        = wpinv_sanitize_amount($amount);
354 354
 
355
-    if ( $calculate ) {
355
+    if ($calculate) {
356 356
         return $amount;
357 357
     }
358 358
 
359 359
     // Fomart the amount.
360
-    return number_format( $amount, $decimals, $decimal_sep, $thousands_sep );
360
+    return number_format($amount, $decimals, $decimal_sep, $thousands_sep);
361 361
 }
362 362
 
363
-function wpinv_sanitize_key( $key ) {
363
+function wpinv_sanitize_key($key) {
364 364
     $raw_key = $key;
365
-    $key = preg_replace( '/[^a-zA-Z0-9_\-\.\:\/]/', '', $key );
365
+    $key = preg_replace('/[^a-zA-Z0-9_\-\.\:\/]/', '', $key);
366 366
 
367
-    return apply_filters( 'wpinv_sanitize_key', $key, $raw_key );
367
+    return apply_filters('wpinv_sanitize_key', $key, $raw_key);
368 368
 }
369 369
 
370 370
 /**
@@ -372,8 +372,8 @@  discard block
 block discarded – undo
372 372
  *
373 373
  * @param $str the file whose extension should be retrieved.
374 374
  */
375
-function wpinv_get_file_extension( $str ) {
376
-    $filetype = wp_check_filetype( $str );
375
+function wpinv_get_file_extension($str) {
376
+    $filetype = wp_check_filetype($str);
377 377
     return $filetype['ext'];
378 378
 }
379 379
 
@@ -382,16 +382,16 @@  discard block
 block discarded – undo
382 382
  *
383 383
  * @param string $string
384 384
  */
385
-function wpinv_string_is_image_url( $string ) {
386
-    $extension = strtolower( wpinv_get_file_extension( $string ) );
387
-    return in_array( $extension, array( 'jpeg', 'jpg', 'png', 'gif', 'ico' ), true );
385
+function wpinv_string_is_image_url($string) {
386
+    $extension = strtolower(wpinv_get_file_extension($string));
387
+    return in_array($extension, array('jpeg', 'jpg', 'png', 'gif', 'ico'), true);
388 388
 }
389 389
 
390 390
 /**
391 391
  * Returns the current URL.
392 392
  */
393 393
 function wpinv_get_current_page_url() {
394
-    return esc_url( add_query_arg( array() ) );
394
+    return esc_url(add_query_arg(array()));
395 395
 }
396 396
 
397 397
 /**
@@ -401,46 +401,46 @@  discard block
 block discarded – undo
401 401
  * @param string $name  Constant name.
402 402
  * @param mixed  $value Value.
403 403
  */
404
-function getpaid_maybe_define_constant( $name, $value ) {
405
-	if ( ! defined( $name ) ) {
406
-		define( $name, $value );
404
+function getpaid_maybe_define_constant($name, $value) {
405
+	if (!defined($name)) {
406
+		define($name, $value);
407 407
 	}
408 408
 }
409 409
 
410 410
 function wpinv_get_php_arg_separator_output() {
411
-	return ini_get( 'arg_separator.output' );
411
+	return ini_get('arg_separator.output');
412 412
 }
413 413
 
414
-function wpinv_rgb_from_hex( $color ) {
415
-    $color = str_replace( '#', '', $color );
414
+function wpinv_rgb_from_hex($color) {
415
+    $color = str_replace('#', '', $color);
416 416
 
417 417
     // Convert shorthand colors to full format, e.g. "FFF" -> "FFFFFF"
418
-    $color = preg_replace( '~^(.)(.)(.)$~', '$1$1$2$2$3$3', $color );
419
-    if ( empty( $color ) ) {
418
+    $color = preg_replace('~^(.)(.)(.)$~', '$1$1$2$2$3$3', $color);
419
+    if (empty($color)) {
420 420
         return null;
421 421
     }
422 422
 
423
-    $color = str_split( $color );
423
+    $color = str_split($color);
424 424
 
425 425
     $rgb      = array();
426
-    $rgb['R'] = hexdec( $color[0] . $color[1] );
427
-    $rgb['G'] = hexdec( $color[2] . $color[3] );
428
-    $rgb['B'] = hexdec( $color[4] . $color[5] );
426
+    $rgb['R'] = hexdec($color[0] . $color[1]);
427
+    $rgb['G'] = hexdec($color[2] . $color[3]);
428
+    $rgb['B'] = hexdec($color[4] . $color[5]);
429 429
 
430 430
     return $rgb;
431 431
 }
432 432
 
433
-function wpinv_hex_darker( $color, $factor = 30 ) {
434
-    $base  = wpinv_rgb_from_hex( $color );
433
+function wpinv_hex_darker($color, $factor = 30) {
434
+    $base  = wpinv_rgb_from_hex($color);
435 435
     $color = '#';
436 436
 
437
-    foreach ( $base as $k => $v ) {
437
+    foreach ($base as $k => $v) {
438 438
         $amount      = $v / 100;
439
-        $amount      = round( $amount * $factor );
439
+        $amount      = round($amount * $factor);
440 440
         $new_decimal = $v - $amount;
441 441
 
442
-        $new_hex_component = dechex( $new_decimal );
443
-        if ( strlen( $new_hex_component ) < 2 ) {
442
+        $new_hex_component = dechex($new_decimal);
443
+        if (strlen($new_hex_component) < 2) {
444 444
             $new_hex_component = '0' . $new_hex_component;
445 445
         }
446 446
         $color .= $new_hex_component;
@@ -449,18 +449,18 @@  discard block
 block discarded – undo
449 449
     return $color;
450 450
 }
451 451
 
452
-function wpinv_hex_lighter( $color, $factor = 30 ) {
453
-    $base  = wpinv_rgb_from_hex( $color );
452
+function wpinv_hex_lighter($color, $factor = 30) {
453
+    $base  = wpinv_rgb_from_hex($color);
454 454
     $color = '#';
455 455
 
456
-    foreach ( $base as $k => $v ) {
456
+    foreach ($base as $k => $v) {
457 457
         $amount      = 255 - $v;
458 458
         $amount      = $amount / 100;
459
-        $amount      = round( $amount * $factor );
459
+        $amount      = round($amount * $factor);
460 460
         $new_decimal = $v + $amount;
461 461
 
462
-        $new_hex_component = dechex( $new_decimal );
463
-        if ( strlen( $new_hex_component ) < 2 ) {
462
+        $new_hex_component = dechex($new_decimal);
463
+        if (strlen($new_hex_component) < 2) {
464 464
             $new_hex_component = '0' . $new_hex_component;
465 465
         }
466 466
         $color .= $new_hex_component;
@@ -469,22 +469,22 @@  discard block
 block discarded – undo
469 469
     return $color;
470 470
 }
471 471
 
472
-function wpinv_light_or_dark( $color, $dark = '#000000', $light = '#FFFFFF' ) {
473
-    $hex = str_replace( '#', '', $color );
472
+function wpinv_light_or_dark($color, $dark = '#000000', $light = '#FFFFFF') {
473
+    $hex = str_replace('#', '', $color);
474 474
 
475
-    $c_r = hexdec( substr( $hex, 0, 2 ) );
476
-    $c_g = hexdec( substr( $hex, 2, 2 ) );
477
-    $c_b = hexdec( substr( $hex, 4, 2 ) );
475
+    $c_r = hexdec(substr($hex, 0, 2));
476
+    $c_g = hexdec(substr($hex, 2, 2));
477
+    $c_b = hexdec(substr($hex, 4, 2));
478 478
 
479
-    $brightness = ( ( $c_r * 299 ) + ( $c_g * 587 ) + ( $c_b * 114 ) ) / 1000;
479
+    $brightness = (($c_r * 299) + ($c_g * 587) + ($c_b * 114)) / 1000;
480 480
 
481 481
     return $brightness > 155 ? $dark : $light;
482 482
 }
483 483
 
484
-function wpinv_format_hex( $hex ) {
485
-    $hex = trim( str_replace( '#', '', $hex ) );
484
+function wpinv_format_hex($hex) {
485
+    $hex = trim(str_replace('#', '', $hex));
486 486
 
487
-    if ( strlen( $hex ) == 3 ) {
487
+    if (strlen($hex) == 3) {
488 488
         $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
489 489
     }
490 490
 
@@ -504,12 +504,12 @@  discard block
 block discarded – undo
504 504
  * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
505 505
  * @return string
506 506
  */
507
-function wpinv_utf8_strimwidth( $str, $start, $width, $trimmaker = '', $encoding = 'UTF-8' ) {
508
-    if ( function_exists( 'mb_strimwidth' ) ) {
509
-        return mb_strimwidth( $str, $start, $width, $trimmaker, $encoding );
507
+function wpinv_utf8_strimwidth($str, $start, $width, $trimmaker = '', $encoding = 'UTF-8') {
508
+    if (function_exists('mb_strimwidth')) {
509
+        return mb_strimwidth($str, $start, $width, $trimmaker, $encoding);
510 510
     }
511 511
 
512
-    return wpinv_utf8_substr( $str, $start, $width, $encoding ) . $trimmaker;
512
+    return wpinv_utf8_substr($str, $start, $width, $encoding) . $trimmaker;
513 513
 }
514 514
 
515 515
 /**
@@ -521,28 +521,28 @@  discard block
 block discarded – undo
521 521
  * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
522 522
  * @return int Returns the number of characters in string.
523 523
  */
524
-function wpinv_utf8_strlen( $str, $encoding = 'UTF-8' ) {
525
-    if ( function_exists( 'mb_strlen' ) ) {
526
-        return mb_strlen( $str, $encoding );
524
+function wpinv_utf8_strlen($str, $encoding = 'UTF-8') {
525
+    if (function_exists('mb_strlen')) {
526
+        return mb_strlen($str, $encoding);
527 527
     }
528 528
 
529
-    return strlen( $str );
529
+    return strlen($str);
530 530
 }
531 531
 
532
-function wpinv_utf8_strtolower( $str, $encoding = 'UTF-8' ) {
533
-    if ( function_exists( 'mb_strtolower' ) ) {
534
-        return mb_strtolower( $str, $encoding );
532
+function wpinv_utf8_strtolower($str, $encoding = 'UTF-8') {
533
+    if (function_exists('mb_strtolower')) {
534
+        return mb_strtolower($str, $encoding);
535 535
     }
536 536
 
537
-    return strtolower( $str );
537
+    return strtolower($str);
538 538
 }
539 539
 
540
-function wpinv_utf8_strtoupper( $str, $encoding = 'UTF-8' ) {
541
-    if ( function_exists( 'mb_strtoupper' ) ) {
542
-        return mb_strtoupper( $str, $encoding );
540
+function wpinv_utf8_strtoupper($str, $encoding = 'UTF-8') {
541
+    if (function_exists('mb_strtoupper')) {
542
+        return mb_strtoupper($str, $encoding);
543 543
     }
544 544
 
545
-    return strtoupper( $str );
545
+    return strtoupper($str);
546 546
 }
547 547
 
548 548
 /**
@@ -556,12 +556,12 @@  discard block
 block discarded – undo
556 556
  * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
557 557
  * @return int Returns the position of the first occurrence of search in the string.
558 558
  */
559
-function wpinv_utf8_strpos( $str, $find, $offset = 0, $encoding = 'UTF-8' ) {
560
-    if ( function_exists( 'mb_strpos' ) ) {
561
-        return mb_strpos( $str, $find, $offset, $encoding );
559
+function wpinv_utf8_strpos($str, $find, $offset = 0, $encoding = 'UTF-8') {
560
+    if (function_exists('mb_strpos')) {
561
+        return mb_strpos($str, $find, $offset, $encoding);
562 562
     }
563 563
 
564
-    return strpos( $str, $find, $offset );
564
+    return strpos($str, $find, $offset);
565 565
 }
566 566
 
567 567
 /**
@@ -575,12 +575,12 @@  discard block
 block discarded – undo
575 575
  * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
576 576
  * @return int Returns the position of the last occurrence of search.
577 577
  */
578
-function wpinv_utf8_strrpos( $str, $find, $offset = 0, $encoding = 'UTF-8' ) {
579
-    if ( function_exists( 'mb_strrpos' ) ) {
580
-        return mb_strrpos( $str, $find, $offset, $encoding );
578
+function wpinv_utf8_strrpos($str, $find, $offset = 0, $encoding = 'UTF-8') {
579
+    if (function_exists('mb_strrpos')) {
580
+        return mb_strrpos($str, $find, $offset, $encoding);
581 581
     }
582 582
 
583
-    return strrpos( $str, $find, $offset );
583
+    return strrpos($str, $find, $offset);
584 584
 }
585 585
 
586 586
 /**
@@ -595,16 +595,16 @@  discard block
 block discarded – undo
595 595
  * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
596 596
  * @return string
597 597
  */
598
-function wpinv_utf8_substr( $str, $start, $length = null, $encoding = 'UTF-8' ) {
599
-    if ( function_exists( 'mb_substr' ) ) {
600
-        if ( null === $length ) {
601
-            return mb_substr( $str, $start, wpinv_utf8_strlen( $str, $encoding ), $encoding );
598
+function wpinv_utf8_substr($str, $start, $length = null, $encoding = 'UTF-8') {
599
+    if (function_exists('mb_substr')) {
600
+        if (null === $length) {
601
+            return mb_substr($str, $start, wpinv_utf8_strlen($str, $encoding), $encoding);
602 602
         } else {
603
-            return mb_substr( $str, $start, $length, $encoding );
603
+            return mb_substr($str, $start, $length, $encoding);
604 604
         }
605 605
     }
606 606
 
607
-    return substr( $str, $start, $length );
607
+    return substr($str, $start, $length);
608 608
 }
609 609
 
610 610
 /**
@@ -616,48 +616,48 @@  discard block
 block discarded – undo
616 616
  * @param string $encoding The encoding parameter is the character encoding. Default "UTF-8".
617 617
  * @return string The width of string.
618 618
  */
619
-function wpinv_utf8_strwidth( $str, $encoding = 'UTF-8' ) {
620
-    if ( function_exists( 'mb_strwidth' ) ) {
621
-        return mb_strwidth( $str, $encoding );
619
+function wpinv_utf8_strwidth($str, $encoding = 'UTF-8') {
620
+    if (function_exists('mb_strwidth')) {
621
+        return mb_strwidth($str, $encoding);
622 622
     }
623 623
 
624
-    return wpinv_utf8_strlen( $str, $encoding );
624
+    return wpinv_utf8_strlen($str, $encoding);
625 625
 }
626 626
 
627
-function wpinv_utf8_ucfirst( $str, $lower_str_end = false, $encoding = 'UTF-8' ) {
628
-    if ( function_exists( 'mb_strlen' ) ) {
629
-        $first_letter = wpinv_utf8_strtoupper( wpinv_utf8_substr( $str, 0, 1, $encoding ), $encoding );
627
+function wpinv_utf8_ucfirst($str, $lower_str_end = false, $encoding = 'UTF-8') {
628
+    if (function_exists('mb_strlen')) {
629
+        $first_letter = wpinv_utf8_strtoupper(wpinv_utf8_substr($str, 0, 1, $encoding), $encoding);
630 630
         $str_end = '';
631 631
 
632
-        if ( $lower_str_end ) {
633
-            $str_end = wpinv_utf8_strtolower( wpinv_utf8_substr( $str, 1, wpinv_utf8_strlen( $str, $encoding ), $encoding ), $encoding );
632
+        if ($lower_str_end) {
633
+            $str_end = wpinv_utf8_strtolower(wpinv_utf8_substr($str, 1, wpinv_utf8_strlen($str, $encoding), $encoding), $encoding);
634 634
         } else {
635
-            $str_end = wpinv_utf8_substr( $str, 1, wpinv_utf8_strlen( $str, $encoding ), $encoding );
635
+            $str_end = wpinv_utf8_substr($str, 1, wpinv_utf8_strlen($str, $encoding), $encoding);
636 636
         }
637 637
 
638 638
         return $first_letter . $str_end;
639 639
     }
640 640
 
641
-    return ucfirst( $str );
641
+    return ucfirst($str);
642 642
 }
643 643
 
644
-function wpinv_utf8_ucwords( $str, $encoding = 'UTF-8' ) {
645
-    if ( function_exists( 'mb_convert_case' ) ) {
646
-        return mb_convert_case( $str, MB_CASE_TITLE, $encoding );
644
+function wpinv_utf8_ucwords($str, $encoding = 'UTF-8') {
645
+    if (function_exists('mb_convert_case')) {
646
+        return mb_convert_case($str, MB_CASE_TITLE, $encoding);
647 647
     }
648 648
 
649
-    return ucwords( $str );
649
+    return ucwords($str);
650 650
 }
651 651
 
652
-function wpinv_period_in_days( $period, $unit ) {
653
-    $period = absint( $period );
652
+function wpinv_period_in_days($period, $unit) {
653
+    $period = absint($period);
654 654
 
655
-    if ( $period > 0 ) {
656
-        if ( in_array( strtolower( $unit ), array( 'w', 'week', 'weeks' ) ) ) {
655
+    if ($period > 0) {
656
+        if (in_array(strtolower($unit), array('w', 'week', 'weeks'))) {
657 657
             $period = $period * 7;
658
-        } elseif ( in_array( strtolower( $unit ), array( 'm', 'month', 'months' ) ) ) {
658
+        } elseif (in_array(strtolower($unit), array('m', 'month', 'months'))) {
659 659
             $period = $period * 30;
660
-        } elseif ( in_array( strtolower( $unit ), array( 'y', 'year', 'years' ) ) ) {
660
+        } elseif (in_array(strtolower($unit), array('y', 'year', 'years'))) {
661 661
             $period = $period * 365;
662 662
         }
663 663
     }
@@ -665,14 +665,14 @@  discard block
 block discarded – undo
665 665
     return $period;
666 666
 }
667 667
 
668
-function wpinv_cal_days_in_month( $calendar, $month, $year ) {
669
-    if ( function_exists( 'cal_days_in_month' ) ) {
670
-        return cal_days_in_month( $calendar, $month, $year );
668
+function wpinv_cal_days_in_month($calendar, $month, $year) {
669
+    if (function_exists('cal_days_in_month')) {
670
+        return cal_days_in_month($calendar, $month, $year);
671 671
     }
672 672
 
673 673
     // Fallback in case the calendar extension is not loaded in PHP
674 674
     // Only supports Gregorian calendar
675
-    return gmdate( 't', mktime( 0, 0, 0, $month, 1, $year ) );
675
+    return gmdate('t', mktime(0, 0, 0, $month, 1, $year));
676 676
 }
677 677
 
678 678
 /**
@@ -683,27 +683,27 @@  discard block
 block discarded – undo
683 683
  *
684 684
  * @return string
685 685
  */
686
-function wpi_help_tip( $tip, $allow_html = false, $is_vue = false, $echo = false ) {
686
+function wpi_help_tip($tip, $allow_html = false, $is_vue = false, $echo = false) {
687 687
 
688
-    if ( $allow_html ) {
689
-        $tip = wpi_sanitize_tooltip( $tip );
688
+    if ($allow_html) {
689
+        $tip = wpi_sanitize_tooltip($tip);
690 690
     } else {
691
-        $tip = strip_tags( $tip );
691
+        $tip = strip_tags($tip);
692 692
     }
693 693
 
694
-    if ( $is_vue ) {
694
+    if ($is_vue) {
695 695
 
696
-        if ( $echo ) {
697
-            echo '<span class="dashicons dashicons-editor-help" title="' . esc_attr( $tip ) . '"></span>';
696
+        if ($echo) {
697
+            echo '<span class="dashicons dashicons-editor-help" title="' . esc_attr($tip) . '"></span>';
698 698
         } else {
699
-            return '<span class="dashicons dashicons-editor-help" title="' . esc_attr( $tip ) . '"></span>';
699
+            return '<span class="dashicons dashicons-editor-help" title="' . esc_attr($tip) . '"></span>';
700 700
         }
701 701
 }
702 702
 
703
-    if ( $echo ) {
704
-        echo '<span class="wpi-help-tip dashicons dashicons-editor-help" title="' . esc_attr( $tip ) . '"></span>';
703
+    if ($echo) {
704
+        echo '<span class="wpi-help-tip dashicons dashicons-editor-help" title="' . esc_attr($tip) . '"></span>';
705 705
     } else {
706
-        return '<span class="wpi-help-tip dashicons dashicons-editor-help" title="' . esc_attr( $tip ) . '"></span>';
706
+        return '<span class="wpi-help-tip dashicons dashicons-editor-help" title="' . esc_attr($tip) . '"></span>';
707 707
     }
708 708
 }
709 709
 
@@ -715,9 +715,9 @@  discard block
 block discarded – undo
715 715
  * @param string $var
716 716
  * @return string
717 717
  */
718
-function wpi_sanitize_tooltip( $var ) {
718
+function wpi_sanitize_tooltip($var) {
719 719
     return wp_kses(
720
-        html_entity_decode( $var ),
720
+        html_entity_decode($var),
721 721
         array(
722 722
 			'br'     => array(),
723 723
 			'em'     => array(),
@@ -740,7 +740,7 @@  discard block
 block discarded – undo
740 740
  */
741 741
 function wpinv_get_screen_ids() {
742 742
 
743
-    $screen_id = sanitize_title( __( 'Invoicing', 'invoicing' ) );
743
+    $screen_id = sanitize_title(__('Invoicing', 'invoicing'));
744 744
 
745 745
     $screen_ids = array(
746 746
         'toplevel_page_' . $screen_id,
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
         'gp-setup', // setup wizard
763 763
     );
764 764
 
765
-    return apply_filters( 'wpinv_screen_ids', $screen_ids );
765
+    return apply_filters('wpinv_screen_ids', $screen_ids);
766 766
 }
767 767
 
768 768
 /**
@@ -773,14 +773,14 @@  discard block
 block discarded – undo
773 773
  * @param array|string $list List of values.
774 774
  * @return array Sanitized array of values.
775 775
  */
776
-function wpinv_parse_list( $list ) {
776
+function wpinv_parse_list($list) {
777 777
 
778
-    if ( empty( $list ) ) {
778
+    if (empty($list)) {
779 779
         $list = array();
780 780
     }
781 781
 
782
-	if ( ! is_array( $list ) ) {
783
-		return preg_split( '/[\s,]+/', $list, -1, PREG_SPLIT_NO_EMPTY );
782
+	if (!is_array($list)) {
783
+		return preg_split('/[\s,]+/', $list, -1, PREG_SPLIT_NO_EMPTY);
784 784
 	}
785 785
 
786 786
 	return $list;
@@ -794,8 +794,8 @@  discard block
 block discarded – undo
794 794
  * @param string $key Type of data to fetch.
795 795
  * @return mixed Fetched data.
796 796
  */
797
-function wpinv_get_data( $key ) {
798
-    return apply_filters( "wpinv_get_$key", include WPINV_PLUGIN_DIR . "includes/data/$key.php" );
797
+function wpinv_get_data($key) {
798
+    return apply_filters("wpinv_get_$key", include WPINV_PLUGIN_DIR . "includes/data/$key.php");
799 799
 }
800 800
 
801 801
 /**
@@ -807,10 +807,10 @@  discard block
 block discarded – undo
807 807
  * @param bool $first_empty Whether or not the first item in the list should be empty
808 808
  * @return mixed Fetched data.
809 809
  */
810
-function wpinv_maybe_add_empty_option( $options, $first_empty ) {
810
+function wpinv_maybe_add_empty_option($options, $first_empty) {
811 811
 
812
-    if ( ! empty( $options ) && $first_empty ) {
813
-        return array_merge( array( '' => '' ), $options );
812
+    if (!empty($options) && $first_empty) {
813
+        return array_merge(array('' => ''), $options);
814 814
     }
815 815
     return $options;
816 816
 
@@ -822,21 +822,21 @@  discard block
 block discarded – undo
822 822
  * @param mixed $var Data to sanitize.
823 823
  * @return string|array
824 824
  */
825
-function wpinv_clean( $var ) {
825
+function wpinv_clean($var) {
826 826
 
827
-	if ( is_array( $var ) ) {
828
-		return array_map( 'wpinv_clean', $var );
827
+	if (is_array($var)) {
828
+		return array_map('wpinv_clean', $var);
829 829
     }
830 830
 
831
-    if ( is_object( $var ) ) {
832
-		$object_vars = get_object_vars( $var );
833
-		foreach ( $object_vars as $property_name => $property_value ) {
834
-			$var->$property_name = wpinv_clean( $property_value );
831
+    if (is_object($var)) {
832
+		$object_vars = get_object_vars($var);
833
+		foreach ($object_vars as $property_name => $property_value) {
834
+			$var->$property_name = wpinv_clean($property_value);
835 835
         }
836 836
         return $var;
837 837
 	}
838 838
 
839
-    return is_string( $var ) ? sanitize_text_field( stripslashes( $var ) ) : $var;
839
+    return is_string($var) ? sanitize_text_field(stripslashes($var)) : $var;
840 840
 }
841 841
 
842 842
 /**
@@ -845,43 +845,43 @@  discard block
 block discarded – undo
845 845
  * @param string $str Data to convert.
846 846
  * @return string|array
847 847
  */
848
-function getpaid_convert_price_string_to_options( $str ) {
848
+function getpaid_convert_price_string_to_options($str) {
849 849
 
850
-	$raw_options = array_map( 'trim', explode( ',', $str ) );
851
-    $options     = array();
850
+	$raw_options = array_map('trim', explode(',', $str));
851
+    $options = array();
852 852
 
853
-    foreach ( $raw_options as $option ) {
853
+    foreach ($raw_options as $option) {
854 854
 
855
-        if ( '' == $option ) {
855
+        if ('' == $option) {
856 856
             continue;
857 857
         }
858 858
 
859
-        $option = array_map( 'trim', explode( '|', $option ) );
859
+        $option = array_map('trim', explode('|', $option));
860 860
 
861 861
         $price = null;
862 862
         $label = null;
863 863
 
864
-        if ( isset( $option[0] ) && '' != $option[0] ) {
865
-            $label  = $option[0];
864
+        if (isset($option[0]) && '' != $option[0]) {
865
+            $label = $option[0];
866 866
         }
867 867
 
868
-        if ( isset( $option[1] ) && '' != $option[1] ) {
868
+        if (isset($option[1]) && '' != $option[1]) {
869 869
             $price = $option[1];
870 870
         }
871 871
 
872
-        if ( ! isset( $price ) ) {
872
+        if (!isset($price)) {
873 873
             $price = $label;
874 874
         }
875 875
 
876
-        if ( ! isset( $price ) || ! is_numeric( $price ) ) {
876
+        if (!isset($price) || !is_numeric($price)) {
877 877
             continue;
878 878
         }
879 879
 
880
-        if ( ! isset( $label ) ) {
880
+        if (!isset($label)) {
881 881
             $label = $price;
882 882
         }
883 883
 
884
-        $options[ "$label|$price" ] = $label;
884
+        $options["$label|$price"] = $label;
885 885
     }
886 886
 
887 887
     return $options;
@@ -890,14 +890,14 @@  discard block
 block discarded – undo
890 890
 /**
891 891
  * Returns the help tip.
892 892
  */
893
-function getpaid_get_help_tip( $tip, $additional_classes = '', $echo = false ) {
893
+function getpaid_get_help_tip($tip, $additional_classes = '', $echo = false) {
894 894
     $classes = 'wpi-help-tip dashicons dashicons-editor-help ' . $additional_classes;
895
-    $tip     = esc_attr( $tip );
895
+    $tip     = esc_attr($tip);
896 896
 
897
-    if ( $echo ) {
898
-        echo '<span class="' . esc_attr( $classes ) . '" data-tip="' . esc_attr( $tip ) . '"></span>';
897
+    if ($echo) {
898
+        echo '<span class="' . esc_attr($classes) . '" data-tip="' . esc_attr($tip) . '"></span>';
899 899
     } else {
900
-        return '<span class="' . esc_attr( $classes ) . '" data-tip="' . esc_attr( $tip ) . '"></span>';
900
+        return '<span class="' . esc_attr($classes) . '" data-tip="' . esc_attr($tip) . '"></span>';
901 901
     }
902 902
 
903 903
 }
@@ -905,18 +905,18 @@  discard block
 block discarded – undo
905 905
 /**
906 906
  * Formats a date
907 907
  */
908
-function getpaid_format_date( $date, $with_time = false ) {
908
+function getpaid_format_date($date, $with_time = false) {
909 909
 
910
-    if ( empty( $date ) || $date == '0000-00-00 00:00:00' ) {
910
+    if (empty($date) || $date == '0000-00-00 00:00:00') {
911 911
         return '';
912 912
     }
913 913
 
914 914
     $format = getpaid_date_format();
915 915
 
916
-    if ( $with_time ) {
916
+    if ($with_time) {
917 917
         $format .= ' ' . getpaid_time_format();
918 918
     }
919
-    return date_i18n( $format, strtotime( $date ) );
919
+    return date_i18n($format, strtotime($date));
920 920
 
921 921
 }
922 922
 
@@ -925,9 +925,9 @@  discard block
 block discarded – undo
925 925
  *
926 926
  * @return string
927 927
  */
928
-function getpaid_format_date_value( $date, $default = '&mdash;', $with_time = false ) {
929
-    $date = getpaid_format_date( $date, $with_time );
930
-    return empty( $date ) ? $default : $date;
928
+function getpaid_format_date_value($date, $default = '&mdash;', $with_time = false) {
929
+    $date = getpaid_format_date($date, $with_time);
930
+    return empty($date) ? $default : $date;
931 931
 }
932 932
 
933 933
 /**
@@ -936,7 +936,7 @@  discard block
 block discarded – undo
936 936
  * @return string
937 937
  */
938 938
 function getpaid_date_format() {
939
-	return apply_filters( 'getpaid_date_format', get_option( 'date_format' ) );
939
+	return apply_filters('getpaid_date_format', get_option('date_format'));
940 940
 }
941 941
 
942 942
 /**
@@ -945,7 +945,7 @@  discard block
 block discarded – undo
945 945
  * @return string
946 946
  */
947 947
 function getpaid_time_format() {
948
-	return apply_filters( 'getpaid_time_format', get_option( 'time_format' ) );
948
+	return apply_filters('getpaid_time_format', get_option('time_format'));
949 949
 }
950 950
 
951 951
 /**
@@ -955,16 +955,16 @@  discard block
 block discarded – undo
955 955
  * @param  integer $limit Limit size in characters.
956 956
  * @return string
957 957
  */
958
-function getpaid_limit_length( $string, $limit ) {
958
+function getpaid_limit_length($string, $limit) {
959 959
     $str_limit = $limit - 3;
960 960
 
961
-	if ( function_exists( 'mb_strimwidth' ) ) {
962
-		if ( mb_strlen( $string ) > $limit ) {
963
-			$string = mb_strimwidth( $string, 0, $str_limit ) . '...';
961
+	if (function_exists('mb_strimwidth')) {
962
+		if (mb_strlen($string) > $limit) {
963
+			$string = mb_strimwidth($string, 0, $str_limit) . '...';
964 964
 		}
965 965
 	} else {
966
-		if ( strlen( $string ) > $limit ) {
967
-			$string = substr( $string, 0, $str_limit ) . '...';
966
+		if (strlen($string) > $limit) {
967
+			$string = substr($string, 0, $str_limit) . '...';
968 968
 		}
969 969
 	}
970 970
     return $string;
@@ -978,7 +978,7 @@  discard block
 block discarded – undo
978 978
  * @since 1.0.19
979 979
  */
980 980
 function getpaid_api() {
981
-    return getpaid()->get( 'api' );
981
+    return getpaid()->get('api');
982 982
 }
983 983
 
984 984
 /**
@@ -988,7 +988,7 @@  discard block
 block discarded – undo
988 988
  * @since 1.0.19
989 989
  */
990 990
 function getpaid_post_types() {
991
-    return getpaid()->get( 'post_types' );
991
+    return getpaid()->get('post_types');
992 992
 }
993 993
 
994 994
 /**
@@ -998,7 +998,7 @@  discard block
 block discarded – undo
998 998
  * @since 1.0.19
999 999
  */
1000 1000
 function getpaid_session() {
1001
-    return getpaid()->get( 'session' );
1001
+    return getpaid()->get('session');
1002 1002
 }
1003 1003
 
1004 1004
 /**
@@ -1008,7 +1008,7 @@  discard block
 block discarded – undo
1008 1008
  * @since 1.0.19
1009 1009
  */
1010 1010
 function getpaid_notes() {
1011
-    return getpaid()->get( 'notes' );
1011
+    return getpaid()->get('notes');
1012 1012
 }
1013 1013
 
1014 1014
 /**
@@ -1017,7 +1017,7 @@  discard block
 block discarded – undo
1017 1017
  * @return GetPaid_Admin
1018 1018
  */
1019 1019
 function getpaid_admin() {
1020
-    return getpaid()->get( 'admin' );
1020
+    return getpaid()->get('admin');
1021 1021
 }
1022 1022
 
1023 1023
 /**
@@ -1027,8 +1027,8 @@  discard block
 block discarded – undo
1027 1027
  * @param string $base the base url
1028 1028
  * @return string
1029 1029
  */
1030
-function getpaid_get_authenticated_action_url( $action, $base = false ) {
1031
-    return wp_nonce_url( add_query_arg( 'getpaid-action', $action, $base ), 'getpaid-nonce', 'getpaid-nonce' );
1030
+function getpaid_get_authenticated_action_url($action, $base = false) {
1031
+    return wp_nonce_url(add_query_arg('getpaid-action', $action, $base), 'getpaid-nonce', 'getpaid-nonce');
1032 1032
 }
1033 1033
 
1034 1034
 /**
@@ -1036,11 +1036,11 @@  discard block
 block discarded – undo
1036 1036
  *
1037 1037
  * @return string
1038 1038
  */
1039
-function getpaid_get_post_type_label( $post_type, $plural = true ) {
1039
+function getpaid_get_post_type_label($post_type, $plural = true) {
1040 1040
 
1041
-    $post_type = get_post_type_object( $post_type );
1041
+    $post_type = get_post_type_object($post_type);
1042 1042
 
1043
-    if ( ! is_object( $post_type ) ) {
1043
+    if (!is_object($post_type)) {
1044 1044
         return null;
1045 1045
     }
1046 1046
 
@@ -1053,18 +1053,18 @@  discard block
 block discarded – undo
1053 1053
  *
1054 1054
  * @return mixed|null
1055 1055
  */
1056
-function getpaid_get_array_field( $array, $key, $secondary_key = null ) {
1056
+function getpaid_get_array_field($array, $key, $secondary_key = null) {
1057 1057
 
1058
-    if ( ! is_array( $array ) ) {
1058
+    if (!is_array($array)) {
1059 1059
         return null;
1060 1060
     }
1061 1061
 
1062
-    if ( ! empty( $secondary_key ) ) {
1063
-        $array = isset( $array[ $secondary_key ] ) ? $array[ $secondary_key ] : array();
1064
-        return getpaid_get_array_field( $array, $key );
1062
+    if (!empty($secondary_key)) {
1063
+        $array = isset($array[$secondary_key]) ? $array[$secondary_key] : array();
1064
+        return getpaid_get_array_field($array, $key);
1065 1065
     }
1066 1066
 
1067
-    return isset( $array[ $key ] ) ? $array[ $key ] : null;
1067
+    return isset($array[$key]) ? $array[$key] : null;
1068 1068
 
1069 1069
 }
1070 1070
 
@@ -1073,12 +1073,12 @@  discard block
 block discarded – undo
1073 1073
  *
1074 1074
  * @return array
1075 1075
  */
1076
-function getpaid_array_merge_if_empty( $args, $defaults ) {
1076
+function getpaid_array_merge_if_empty($args, $defaults) {
1077 1077
 
1078
-    foreach ( $defaults as $key => $value ) {
1078
+    foreach ($defaults as $key => $value) {
1079 1079
 
1080
-        if ( empty( $args[ $key ] ) ) {
1081
-            $args[ $key ] = $value;
1080
+        if (empty($args[$key])) {
1081
+            $args[$key] = $value;
1082 1082
         }
1083 1083
     }
1084 1084
 
@@ -1095,12 +1095,12 @@  discard block
 block discarded – undo
1095 1095
 
1096 1096
     $types = get_allowed_mime_types();
1097 1097
 
1098
-    if ( isset( $types['htm|html'] ) ) {
1099
-		unset( $types['htm|html'] );
1098
+    if (isset($types['htm|html'])) {
1099
+		unset($types['htm|html']);
1100 1100
 	}
1101 1101
 
1102
-    if ( isset( $types['js'] ) ) {
1103
-		unset( $types['js'] );
1102
+    if (isset($types['js'])) {
1103
+		unset($types['js']);
1104 1104
 	}
1105 1105
 
1106 1106
     return $types;
@@ -1108,21 +1108,21 @@  discard block
 block discarded – undo
1108 1108
 }
1109 1109
 
1110 1110
 
1111
-function getpaid_user_delete_invoice( $data ) {
1111
+function getpaid_user_delete_invoice($data) {
1112 1112
 
1113 1113
     // Ensure there is an invoice to delete.
1114
-    if ( empty( $data['invoice_id'] ) ) {
1114
+    if (empty($data['invoice_id'])) {
1115 1115
         return;
1116 1116
     }
1117 1117
 
1118
-    $invoice = new WPInv_Invoice( (int) $data['invoice_id'] );
1118
+    $invoice = new WPInv_Invoice((int) $data['invoice_id']);
1119 1119
 
1120 1120
     // Ensure that it exists and that it belongs to the current user.
1121
-    if ( ! $invoice->exists() || $invoice->get_customer_id() != get_current_user_id() ) {
1121
+    if (!$invoice->exists() || $invoice->get_customer_id() != get_current_user_id()) {
1122 1122
         $notice = 'perm_delete_invoice';
1123 1123
 
1124 1124
     // Can it be deleted?
1125
-    } elseif ( ! $invoice->needs_payment() ) {
1125
+    } elseif (!$invoice->needs_payment()) {
1126 1126
         $notice = 'cannot_delete_invoice';
1127 1127
 
1128 1128
     // Delete it.
@@ -1141,8 +1141,8 @@  discard block
 block discarded – undo
1141 1141
         )
1142 1142
     );
1143 1143
 
1144
-    wp_safe_redirect( $redirect );
1144
+    wp_safe_redirect($redirect);
1145 1145
     exit;
1146 1146
 
1147 1147
 }
1148
-add_action( 'getpaid_authenticated_action_delete_invoice', 'getpaid_user_delete_invoice' );
1148
+add_action('getpaid_authenticated_action_delete_invoice', 'getpaid_user_delete_invoice');
Please login to merge, or discard this patch.
includes/api/class-getpaid-rest-report-sales-controller.php 2 patches
Indentation   +679 added lines, -679 removed lines patch added patch discarded remove patch
@@ -18,688 +18,688 @@
 block discarded – undo
18 18
  */
19 19
 class GetPaid_REST_Report_Sales_Controller extends GetPaid_REST_Date_Based_Controller {
20 20
 
21
-	/**
22
-	 * Route base.
23
-	 *
24
-	 * @var string
25
-	 */
26
-	protected $rest_base = 'reports/sales';
27
-
28
-	/**
29
-	 * The report data.
30
-	 *
31
-	 * @var stdClass
32
-	 */
33
-	public $report_data;
34
-
35
-	/**
36
-	 * The report range.
37
-	 *
38
-	 * @var array
39
-	 */
40
-	public $report_range;
41
-
42
-	/**
43
-	 * Registers the routes for the objects of the controller.
44
-	 *
45
-	 * @since 2.0.0
46
-	 *
47
-	 * @see register_rest_route()
48
-	 */
49
-	public function register_namespace_routes( $namespace ) {
50
-
51
-		// Get sales report.
52
-		register_rest_route(
53
-			$namespace,
54
-			$this->rest_base,
55
-			array(
56
-				array(
57
-					'methods'             => WP_REST_Server::READABLE,
58
-					'callback'            => array( $this, 'get_items' ),
59
-					'permission_callback' => array( $this, 'get_items_permissions_check' ),
60
-					'args'                => $this->get_collection_params(),
61
-				),
62
-				'schema' => array( $this, 'get_public_item_schema' ),
63
-			)
64
-		);
65
-
66
-	}
67
-
68
-	/**
69
-	 * Makes sure the current user has access to READ the report APIs.
70
-	 *
71
-	 * @since  2.0.0
72
-	 * @param WP_REST_Request $request Full data about the request.
73
-	 * @return WP_Error|boolean
74
-	 */
75
-	public function get_items_permissions_check( $request ) {
76
-
77
-		if ( ! wpinv_current_user_can_manage_invoicing() ) {
78
-			return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot list resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
79
-		}
80
-
81
-		return true;
82
-	}
83
-
84
-	/**
85
-	 * Get sales reports.
86
-	 *
87
-	 * @param WP_REST_Request $request
88
-	 * @return array|WP_Error
89
-	 */
90
-	public function get_items( $request ) {
91
-		$data   = array();
92
-		$item   = $this->prepare_item_for_response( null, $request );
93
-		$data[] = $this->prepare_response_for_collection( $item );
94
-
95
-		return rest_ensure_response( $data );
96
-	}
97
-
98
-	/**
99
-	 * Prepare a report sales object for serialization.
100
-	 *
101
-	 * @param null $_
102
-	 * @param WP_REST_Request $request Request object.
103
-	 * @return WP_REST_Response $response Response data.
104
-	 */
105
-	public function prepare_item_for_response( $_, $request ) {
106
-
107
-		// Set report range.
108
-		$this->report_range = $this->get_date_range( $request );
109
-
110
-		$report_data     = $this->get_report_data();
111
-		$period_totals   = array();
112
-
113
-		// Setup period totals by ensuring each period in the interval has data.
114
-		$start_date      = strtotime( $this->report_range['after'] );
115
-
116
-		if ( 'month' === $this->groupby ) {
117
-			$start_date      = strtotime( gmdate( 'Y-m-01', $start_date ) );
118
-		}
119
-
120
-		for ( $i = 0; $i < $this->interval; $i++ ) {
121
-
122
-			switch ( $this->groupby ) {
123
-				case 'day':
124
-					$time = gmdate( 'Y-m-d', strtotime( "+{$i} DAY", $start_date ) );
125
-					break;
126
-				default:
127
-					$time = gmdate( 'Y-m', strtotime( "+{$i} MONTH", $start_date ) );
128
-					break;
129
-			}
130
-
131
-			// Set the defaults for each period.
132
-			$period_totals[ $time ] = array(
133
-				'invoices'          => 0,
134
-				'items'             => 0,
135
-				'refunded_items'    => 0,
136
-				'refunded_tax'      => wpinv_round_amount( 0.00 ),
137
-				'subtotal'          => wpinv_round_amount( 0.00 ),
138
-				'refunded_subtotal' => wpinv_round_amount( 0.00 ),
139
-				'refunded_fees'     => wpinv_round_amount( 0.00 ),
140
-				'discount'          => wpinv_round_amount( 0.00 ),
141
-			);
142
-
143
-			foreach ( array_keys( wpinv_get_report_graphs() ) as $key ) {
144
-				if ( ! isset( $period_totals[ $time ][ $key ] ) ) {
145
-					$period_totals[ $time ][ $key ] = wpinv_round_amount( 0.00 );
146
-				}
147
-			}
148
-		}
149
-
150
-		// add total sales, total invoice count, total tax for each period
151
-		$date_format = ( 'day' === $this->groupby ) ? 'Y-m-d' : 'Y-m';
152
-		foreach ( $report_data->invoices as $invoice ) {
153
-			$time = gmdate( $date_format, strtotime( $invoice->post_date ) );
154
-
155
-			if ( ! isset( $period_totals[ $time ] ) ) {
156
-				continue;
157
-			}
158
-
159
-			$period_totals[ $time ]['sales']    = wpinv_round_amount( $invoice->total_sales );
160
-			$period_totals[ $time ]['tax']      = wpinv_round_amount( $invoice->total_tax );
161
-			$period_totals[ $time ]['subtotal'] = wpinv_round_amount( $invoice->subtotal );
162
-			$period_totals[ $time ]['fees']     = wpinv_round_amount( $invoice->total_fees );
163
-
164
-		}
165
-
166
-		foreach ( $report_data->refunds as $invoice ) {
167
-			$time = gmdate( $date_format, strtotime( $invoice->post_date ) );
168
-
169
-			if ( ! isset( $period_totals[ $time ] ) ) {
170
-				continue;
171
-			}
172
-
173
-			$period_totals[ $time ]['refunds']           = wpinv_round_amount( $invoice->total_sales );
174
-			$period_totals[ $time ]['refunded_tax']      = wpinv_round_amount( $invoice->total_tax );
175
-			$period_totals[ $time ]['refunded_subtotal'] = wpinv_round_amount( $invoice->subtotal );
176
-			$period_totals[ $time ]['refunded_fees']     = wpinv_round_amount( $invoice->total_fees );
177
-
178
-		}
179
-
180
-		foreach ( $report_data->invoice_counts as $invoice ) {
181
-			$time = gmdate( $date_format, strtotime( $invoice->post_date ) );
182
-
183
-			if ( isset( $period_totals[ $time ] ) ) {
184
-				$period_totals[ $time ]['invoices']   = (int) $invoice->count;
185
-			}
186
-		}
187
-
188
-		// Add total invoice items for each period.
189
-		foreach ( $report_data->invoice_items as $invoice_item ) {
190
-			$time = ( 'day' === $this->groupby ) ? gmdate( 'Y-m-d', strtotime( $invoice_item->post_date ) ) : gmdate( 'Y-m', strtotime( $invoice_item->post_date ) );
191
-
192
-			if ( isset( $period_totals[ $time ] ) ) {
193
-				$period_totals[ $time ]['items'] = (int) $invoice_item->invoice_item_count;
194
-			}
195
-		}
196
-
197
-		// Add total discount for each period.
198
-		foreach ( $report_data->coupons as $discount ) {
199
-			$time = ( 'day' === $this->groupby ) ? gmdate( 'Y-m-d', strtotime( $discount->post_date ) ) : gmdate( 'Y-m', strtotime( $discount->post_date ) );
200
-
201
-			if ( isset( $period_totals[ $time ] ) ) {
202
-				$period_totals[ $time ]['discount'] = wpinv_round_amount( $discount->discount_amount );
203
-			}
204
-		}
205
-
206
-		// Extra fields.
207
-		foreach ( array_keys( wpinv_get_report_graphs() ) as $key ) {
208
-
209
-			// Abort unprepared.
210
-			if ( ! isset( $report_data->$key ) ) {
211
-				continue;
212
-			}
213
-
214
-			// Abort defaults.
215
-			if ( in_array( $key, array( 'sales', 'refunds', 'tax', 'fees', 'discount', 'invoices', 'items' ) ) ) {
216
-				continue;
217
-			}
218
-
219
-			// Set values.
220
-			foreach ( $report_data->$key as $item ) {
221
-				$time = ( 'day' === $this->groupby ) ? gmdate( 'Y-m-d', strtotime( $item->date ) ) : gmdate( 'Y-m', strtotime( $item->date ) );
222
-
223
-				if ( isset( $period_totals[ $time ] ) ) {
224
-					$period_totals[ $time ][ $key ] = wpinv_round_amount( $item->val );
225
-				}
226
-			}
227
-
228
-			unset( $report_data->$key );
229
-		}
230
-
231
-		$report_data->totals            = $period_totals;
232
-		$report_data->grouped_by        = $this->groupby;
233
-		$report_data->interval          = max( $this->interval, 1 );
234
-		$report_data->currency          = wpinv_get_currency();
235
-		$report_data->currency_symbol   = wpinv_currency_symbol();
236
-		$report_data->currency_position = wpinv_currency_position();
237
-		$report_data->decimal_places    = wpinv_decimals();
238
-		$report_data->thousands_sep     = wpinv_thousands_separator();
239
-		$report_data->decimals_sep      = wpinv_decimal_separator();
240
-		$report_data->start_date        = gmdate( 'Y-m-d', strtotime( $this->report_range['after'] ) );
241
-		$report_data->end_date          = gmdate( 'Y-m-d', strtotime( $this->report_range['before'] ) );
242
-		$report_data->start_date_locale = getpaid_format_date( gmdate( 'Y-m-d', strtotime( $this->report_range['after'] ) ) );
243
-		$report_data->end_date_locale   = getpaid_format_date( gmdate( 'Y-m-d', strtotime( $this->report_range['before'] ) ) );
244
-		$report_data->decimals_sep      = wpinv_decimal_separator();
245
-
246
-		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
247
-		$data    = $report_data;
248
-		unset( $data->invoice_counts, $data->invoices, $data->coupons, $data->refunds, $data->invoice_items );
249
-		$data    = $this->add_additional_fields_to_object( (array) $data, $request );
250
-		$data    = $this->filter_response_by_context( $data, $context );
251
-
252
-		// Wrap the data in a response object.
253
-		$response = rest_ensure_response( $data );
254
-		$response->add_links(
21
+    /**
22
+     * Route base.
23
+     *
24
+     * @var string
25
+     */
26
+    protected $rest_base = 'reports/sales';
27
+
28
+    /**
29
+     * The report data.
30
+     *
31
+     * @var stdClass
32
+     */
33
+    public $report_data;
34
+
35
+    /**
36
+     * The report range.
37
+     *
38
+     * @var array
39
+     */
40
+    public $report_range;
41
+
42
+    /**
43
+     * Registers the routes for the objects of the controller.
44
+     *
45
+     * @since 2.0.0
46
+     *
47
+     * @see register_rest_route()
48
+     */
49
+    public function register_namespace_routes( $namespace ) {
50
+
51
+        // Get sales report.
52
+        register_rest_route(
53
+            $namespace,
54
+            $this->rest_base,
255 55
             array(
256
-				'about' => array(
257
-					'href' => rest_url( sprintf( '%s/reports', $this->namespace ) ),
258
-				),
56
+                array(
57
+                    'methods'             => WP_REST_Server::READABLE,
58
+                    'callback'            => array( $this, 'get_items' ),
59
+                    'permission_callback' => array( $this, 'get_items_permissions_check' ),
60
+                    'args'                => $this->get_collection_params(),
61
+                ),
62
+                'schema' => array( $this, 'get_public_item_schema' ),
259 63
             )
260 64
         );
261 65
 
262
-		return apply_filters( 'getpaid_rest_prepare_report_sales', $response, $report_data, $request );
263
-	}
264
-
265
-	/**
266
-	 * Get report data.
267
-	 *
268
-	 * @return stdClass
269
-	 */
270
-	public function get_report_data() {
271
-		if ( empty( $this->report_data ) ) {
272
-			$this->query_report_data();
273
-		}
274
-		return $this->report_data;
275
-	}
276
-
277
-	/**
278
-	 * Get all data needed for this report and store in the class.
279
-	 */
280
-	protected function query_report_data() {
281
-
282
-		// Prepare reports.
283
-		$this->report_data = (object) array(
284
-			'invoice_counts' => $this->query_invoice_counts(), //count, post_date
285
-			'coupons'        => $this->query_coupon_counts(), // discount_amount, post_date
286
-			'invoice_items'  => $this->query_item_counts(), // invoice_item_count, post_date
287
-			'refunded_items' => $this->count_refunded_items(), // invoice_item_count, post_date
288
-			'invoices'       => $this->query_invoice_totals(), // total_sales, total_tax, total_discount, total_fees, subtotal, post_date
289
-			'refunds'        => $this->query_refunded_totals(), // total_sales, total_tax, total_discount, total_fees, subtotal, post_date
290
-			'previous_range' => $this->previous_range,
291
-		);
292
-
293
-		// Calculated totals.
294
-		$this->report_data->total_tax          = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_tax' ) ) );
295
-		$this->report_data->total_sales        = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_sales' ) ) );
296
-		$this->report_data->total_discount     = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_discount' ) ) );
297
-		$this->report_data->total_fees         = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_fees' ) ) );
298
-		$this->report_data->subtotal           = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'subtotal' ) ) );
299
-		$this->report_data->net_sales          = wpinv_round_amount( $this->report_data->total_sales - max( 0, $this->report_data->total_tax ) );
300
-		$this->report_data->total_refunded_tax = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_tax' ) ) );
301
-		$this->report_data->total_refunds      = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_sales' ) ) );
302
-		$this->report_data->refunded_discount  = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_discount' ) ) );
303
-		$this->report_data->refunded_fees      = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_fees' ) ) );
304
-		$this->report_data->refunded_subtotal  = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'subtotal' ) ) );
305
-		$this->report_data->net_refunds        = wpinv_round_amount( $this->report_data->total_refunds + max( 0, $this->report_data->total_refunded_tax ) );
306
-
307
-		// Calculate average based on net.
308
-		$this->report_data->average_sales       = wpinv_round_amount( $this->report_data->net_sales / max( $this->interval, 1 ), 2 );
309
-		$this->report_data->average_total_sales = wpinv_round_amount( $this->report_data->total_sales / max( $this->interval, 1 ), 2 );
310
-
311
-		// Total invoices in this period, even if refunded.
312
-		$this->report_data->total_invoices = absint( array_sum( wp_list_pluck( $this->report_data->invoice_counts, 'count' ) ) );
313
-
314
-		// Items invoiced in this period, even if refunded.
315
-		$this->report_data->total_items = absint( array_sum( wp_list_pluck( $this->report_data->invoice_items, 'invoice_item_count' ) ) );
316
-
317
-		// 3rd party filtering of report data
318
-		$this->report_data = apply_filters( 'getpaid_rest_api_filter_report_data', $this->report_data, $this );
319
-	}
320
-
321
-	/**
322
-	 * Prepares invoice counts.
323
-	 *
324
-	 * @return array.
325
-	 */
326
-	protected function query_invoice_counts() {
327
-
328
-		return (array) GetPaid_Reports_Helper::get_invoice_report_data(
329
-			array(
330
-				'data'           => array(
331
-					'ID'        => array(
332
-						'type'     => 'post_data',
333
-						'function' => 'COUNT',
334
-						'name'     => 'count',
335
-						'distinct' => true,
336
-					),
337
-					'post_date' => array(
338
-						'type'     => 'post_data',
339
-						'function' => 'MIN',
340
-						'name'     => 'post_date',
341
-					),
342
-				),
343
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
344
-				'order_by'       => 'post_date ASC',
345
-				'query_type'     => 'get_results',
346
-				'filter_range'   => $this->report_range,
347
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded', 'wpi-renewal' ),
348
-			)
349
-		);
350
-
351
-	}
352
-
353
-	/**
354
-	 * Prepares coupon counts.
355
-	 *
356
-	 * @return array.
357
-	 */
358
-	protected function query_coupon_counts() {
359
-
360
-		return (array) GetPaid_Reports_Helper::get_invoice_report_data(
361
-			array(
362
-				'data'           => array(
363
-					'discount'  => array(
364
-						'type'     => 'invoice_data',
365
-						'function' => 'SUM',
366
-						'name'     => 'discount_amount',
367
-					),
368
-					'post_date' => array(
369
-						'type'     => 'post_data',
370
-						'function' => 'MIN',
371
-						'name'     => 'post_date',
372
-					),
373
-				),
374
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
375
-				'order_by'       => 'post_date ASC',
376
-				'query_type'     => 'get_results',
377
-				'filter_range'   => $this->report_range,
378
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded', 'wpi-renewal' ),
379
-			)
380
-		);
381
-
382
-	}
383
-
384
-	/**
385
-	 * Prepares item counts.
386
-	 *
387
-	 * @return array.
388
-	 */
389
-	protected function query_item_counts() {
390
-
391
-		return (array) GetPaid_Reports_Helper::get_invoice_report_data(
392
-			array(
393
-				'data'           => array(
394
-					'quantity'  => array(
395
-						'type'     => 'invoice_item',
396
-						'function' => 'SUM',
397
-						'name'     => 'invoice_item_count',
398
-					),
399
-					'post_date' => array(
400
-						'type'     => 'post_data',
401
-						'function' => 'MIN',
402
-						'name'     => 'post_date',
403
-					),
404
-				),
405
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
406
-				'order_by'       => 'post_date ASC',
407
-				'query_type'     => 'get_results',
408
-				'filter_range'   => $this->report_range,
409
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded', 'wpi-renewal' ),
410
-			)
411
-		);
412
-
413
-	}
414
-
415
-	/**
416
-	 * Prepares refunded item counts.
417
-	 *
418
-	 * @return array.
419
-	 */
420
-	protected function count_refunded_items() {
421
-
422
-		return (int) GetPaid_Reports_Helper::get_invoice_report_data(
423
-			array(
424
-				'data'           => array(
425
-					'quantity' => array(
426
-						'type'     => 'invoice_item',
427
-						'function' => 'SUM',
428
-						'name'     => 'invoice_item_count',
429
-					),
430
-				),
431
-				'query_type'     => 'get_var',
432
-				'filter_range'   => $this->report_range,
433
-				'invoice_status' => array( 'wpi-refunded' ),
434
-			)
435
-		);
436
-
437
-	}
438
-
439
-	/**
440
-	 * Prepares daily invoice totals.
441
-	 *
442
-	 * @return array.
443
-	 */
444
-	protected function query_invoice_totals() {
445
-
446
-		return (array) GetPaid_Reports_Helper::get_invoice_report_data(
447
-			array(
448
-				'data'           => array(
449
-					'total'      => array(
450
-						'type'     => 'invoice_data',
451
-						'function' => 'SUM',
452
-						'name'     => 'total_sales',
453
-					),
454
-					'tax'        => array(
455
-						'type'     => 'invoice_data',
456
-						'function' => 'SUM',
457
-						'name'     => 'total_tax',
458
-					),
459
-					'discount'   => array(
460
-						'type'     => 'invoice_data',
461
-						'function' => 'SUM',
462
-						'name'     => 'total_discount',
463
-					),
464
-					'fees_total' => array(
465
-						'type'     => 'invoice_data',
466
-						'function' => 'SUM',
467
-						'name'     => 'total_fees',
468
-					),
469
-					'subtotal'   => array(
470
-						'type'     => 'invoice_data',
471
-						'function' => 'SUM',
472
-						'name'     => 'subtotal',
473
-					),
474
-					'post_date'  => array(
475
-						'type'     => 'post_data',
476
-						'function' => '',
477
-						'name'     => 'post_date',
478
-					),
479
-				),
480
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
481
-				'order_by'       => 'post_date ASC',
482
-				'query_type'     => 'get_results',
483
-				'filter_range'   => $this->report_range,
484
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-renewal' ),
485
-			)
486
-		);
487
-
488
-	}
489
-
490
-	/**
491
-	 * Prepares daily invoice totals.
492
-	 *
493
-	 * @return array.
494
-	 */
495
-	protected function query_refunded_totals() {
496
-
497
-		return (array) GetPaid_Reports_Helper::get_invoice_report_data(
498
-			array(
499
-				'data'           => array(
500
-					'total'      => array(
501
-						'type'     => 'invoice_data',
502
-						'function' => 'SUM',
503
-						'name'     => 'total_sales',
504
-					),
505
-					'tax'        => array(
506
-						'type'     => 'invoice_data',
507
-						'function' => 'SUM',
508
-						'name'     => 'total_tax',
509
-					),
510
-					'discount'   => array(
511
-						'type'     => 'invoice_data',
512
-						'function' => 'SUM',
513
-						'name'     => 'total_discount',
514
-					),
515
-					'fees_total' => array(
516
-						'type'     => 'invoice_data',
517
-						'function' => 'SUM',
518
-						'name'     => 'total_fees',
519
-					),
520
-					'subtotal'   => array(
521
-						'type'     => 'invoice_data',
522
-						'function' => 'SUM',
523
-						'name'     => 'subtotal',
524
-					),
525
-					'post_date'  => array(
526
-						'type'     => 'post_data',
527
-						'function' => '',
528
-						'name'     => 'post_date',
529
-					),
530
-				),
531
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
532
-				'order_by'       => 'post_date ASC',
533
-				'query_type'     => 'get_results',
534
-				'filter_range'   => $this->report_range,
535
-				'invoice_status' => array( 'wpi-refunded' ),
536
-			)
537
-		);
538
-
539
-	}
540
-
541
-	/**
542
-	 * Get the Report's schema, conforming to JSON Schema.
543
-	 *
544
-	 * @return array
545
-	 */
546
-	public function get_item_schema() {
547
-
548
-		$schema = array(
549
-			'$schema'    => 'http://json-schema.org/draft-04/schema#',
550
-			'title'      => 'sales_report',
551
-			'type'       => 'object',
552
-			'properties' => array(
553
-				'total_sales'         => array(
554
-					'description' => __( 'Gross sales in the period.', 'invoicing' ),
555
-					'type'        => 'string',
556
-					'context'     => array( 'view' ),
557
-					'readonly'    => true,
558
-				),
559
-				'net_sales'           => array(
560
-					'description' => __( 'Net sales in the period.', 'invoicing' ),
561
-					'type'        => 'string',
562
-					'context'     => array( 'view' ),
563
-					'readonly'    => true,
564
-				),
565
-				'average_sales'       => array(
566
-					'description' => __( 'Average net daily sales.', 'invoicing' ),
567
-					'type'        => 'string',
568
-					'context'     => array( 'view' ),
569
-					'readonly'    => true,
570
-				),
571
-				'average_total_sales' => array(
572
-					'description' => __( 'Average gross daily sales.', 'invoicing' ),
573
-					'type'        => 'string',
574
-					'context'     => array( 'view' ),
575
-					'readonly'    => true,
576
-				),
577
-				'total_invoices'      => array(
578
-					'description' => __( 'Number of paid invoices.', 'invoicing' ),
579
-					'type'        => 'integer',
580
-					'context'     => array( 'view' ),
581
-					'readonly'    => true,
582
-				),
583
-				'total_items'         => array(
584
-					'description' => __( 'Number of items purchased.', 'invoicing' ),
585
-					'type'        => 'integer',
586
-					'context'     => array( 'view' ),
587
-					'readonly'    => true,
588
-				),
589
-				'refunded_items'      => array(
590
-					'description' => __( 'Number of items refunded.', 'invoicing' ),
591
-					'type'        => 'integer',
592
-					'context'     => array( 'view' ),
593
-					'readonly'    => true,
594
-				),
595
-				'total_tax'           => array(
596
-					'description' => __( 'Total charged for taxes.', 'invoicing' ),
597
-					'type'        => 'string',
598
-					'context'     => array( 'view' ),
599
-					'readonly'    => true,
600
-				),
601
-				'total_refunded_tax'  => array(
602
-					'description' => __( 'Total refunded for taxes.', 'invoicing' ),
603
-					'type'        => 'string',
604
-					'context'     => array( 'view' ),
605
-					'readonly'    => true,
606
-				),
607
-				'total_fees'          => array(
608
-					'description' => __( 'Total fees charged.', 'invoicing' ),
609
-					'type'        => 'string',
610
-					'context'     => array( 'view' ),
611
-					'readonly'    => true,
612
-				),
613
-				'total_refunds'       => array(
614
-					'description' => __( 'Total of refunded invoices.', 'invoicing' ),
615
-					'type'        => 'integer',
616
-					'context'     => array( 'view' ),
617
-					'readonly'    => true,
618
-				),
619
-				'net_refunds'         => array(
620
-					'description' => __( 'Net of refunded invoices.', 'invoicing' ),
621
-					'type'        => 'integer',
622
-					'context'     => array( 'view' ),
623
-					'readonly'    => true,
624
-				),
625
-				'total_discount'      => array(
626
-					'description' => __( 'Total of discounts used.', 'invoicing' ),
627
-					'type'        => 'integer',
628
-					'context'     => array( 'view' ),
629
-					'readonly'    => true,
630
-				),
631
-				'totals'              => array(
632
-					'description' => __( 'Totals.', 'invoicing' ),
633
-					'type'        => 'array',
634
-					'items'       => array(
635
-						'type' => 'array',
636
-					),
637
-					'context'     => array( 'view' ),
638
-					'readonly'    => true,
639
-				),
640
-				'interval'            => array(
641
-					'description' => __( 'Number of months/days in the report period.', 'invoicing' ),
642
-					'type'        => 'integer',
643
-					'context'     => array( 'view' ),
644
-					'readonly'    => true,
645
-				),
646
-				'previous_range'      => array(
647
-					'description' => __( 'The previous report period.', 'invoicing' ),
648
-					'type'        => 'array',
649
-					'items'       => array(
650
-						'type' => 'string',
651
-					),
652
-					'context'     => array( 'view' ),
653
-					'readonly'    => true,
654
-				),
655
-				'grouped_by'          => array(
656
-					'description' => __( 'The period used to group the totals.', 'invoicing' ),
657
-					'type'        => 'string',
658
-					'context'     => array( 'view' ),
659
-					'enum'        => array( 'day', 'month' ),
660
-					'readonly'    => true,
661
-				),
662
-				'currency'            => array(
663
-					'description' => __( 'The default store currency.', 'invoicing' ),
664
-					'type'        => 'string',
665
-					'context'     => array( 'view' ),
666
-					'readonly'    => true,
667
-				),
668
-				'currency_symbol'     => array(
669
-					'description' => __( 'The default store currency symbol.', 'invoicing' ),
670
-					'type'        => 'string',
671
-					'context'     => array( 'view' ),
672
-					'readonly'    => true,
673
-				),
674
-				'currency_position'   => array(
675
-					'description' => __( 'The default store currency position.', 'invoicing' ),
676
-					'type'        => 'string',
677
-					'context'     => array( 'view' ),
678
-					'readonly'    => true,
679
-				),
680
-				'decimal_places'      => array(
681
-					'description' => __( 'The default store decimal places.', 'invoicing' ),
682
-					'type'        => 'string',
683
-					'context'     => array( 'view' ),
684
-					'readonly'    => true,
685
-				),
686
-				'thousands_sep'       => array(
687
-					'description' => __( 'The default store thousands separator.', 'invoicing' ),
688
-					'type'        => 'string',
689
-					'context'     => array( 'view' ),
690
-					'readonly'    => true,
691
-				),
692
-				'decimals_sep'        => array(
693
-					'description' => __( 'The default store decimals separator.', 'invoicing' ),
694
-					'type'        => 'string',
695
-					'context'     => array( 'view' ),
696
-					'readonly'    => true,
697
-				),
698
-			),
699
-		);
700
-
701
-		return $this->add_additional_fields_schema( $schema );
702
-
703
-	}
66
+    }
67
+
68
+    /**
69
+     * Makes sure the current user has access to READ the report APIs.
70
+     *
71
+     * @since  2.0.0
72
+     * @param WP_REST_Request $request Full data about the request.
73
+     * @return WP_Error|boolean
74
+     */
75
+    public function get_items_permissions_check( $request ) {
76
+
77
+        if ( ! wpinv_current_user_can_manage_invoicing() ) {
78
+            return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot list resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
79
+        }
80
+
81
+        return true;
82
+    }
83
+
84
+    /**
85
+     * Get sales reports.
86
+     *
87
+     * @param WP_REST_Request $request
88
+     * @return array|WP_Error
89
+     */
90
+    public function get_items( $request ) {
91
+        $data   = array();
92
+        $item   = $this->prepare_item_for_response( null, $request );
93
+        $data[] = $this->prepare_response_for_collection( $item );
94
+
95
+        return rest_ensure_response( $data );
96
+    }
97
+
98
+    /**
99
+     * Prepare a report sales object for serialization.
100
+     *
101
+     * @param null $_
102
+     * @param WP_REST_Request $request Request object.
103
+     * @return WP_REST_Response $response Response data.
104
+     */
105
+    public function prepare_item_for_response( $_, $request ) {
106
+
107
+        // Set report range.
108
+        $this->report_range = $this->get_date_range( $request );
109
+
110
+        $report_data     = $this->get_report_data();
111
+        $period_totals   = array();
112
+
113
+        // Setup period totals by ensuring each period in the interval has data.
114
+        $start_date      = strtotime( $this->report_range['after'] );
115
+
116
+        if ( 'month' === $this->groupby ) {
117
+            $start_date      = strtotime( gmdate( 'Y-m-01', $start_date ) );
118
+        }
119
+
120
+        for ( $i = 0; $i < $this->interval; $i++ ) {
121
+
122
+            switch ( $this->groupby ) {
123
+                case 'day':
124
+                    $time = gmdate( 'Y-m-d', strtotime( "+{$i} DAY", $start_date ) );
125
+                    break;
126
+                default:
127
+                    $time = gmdate( 'Y-m', strtotime( "+{$i} MONTH", $start_date ) );
128
+                    break;
129
+            }
130
+
131
+            // Set the defaults for each period.
132
+            $period_totals[ $time ] = array(
133
+                'invoices'          => 0,
134
+                'items'             => 0,
135
+                'refunded_items'    => 0,
136
+                'refunded_tax'      => wpinv_round_amount( 0.00 ),
137
+                'subtotal'          => wpinv_round_amount( 0.00 ),
138
+                'refunded_subtotal' => wpinv_round_amount( 0.00 ),
139
+                'refunded_fees'     => wpinv_round_amount( 0.00 ),
140
+                'discount'          => wpinv_round_amount( 0.00 ),
141
+            );
142
+
143
+            foreach ( array_keys( wpinv_get_report_graphs() ) as $key ) {
144
+                if ( ! isset( $period_totals[ $time ][ $key ] ) ) {
145
+                    $period_totals[ $time ][ $key ] = wpinv_round_amount( 0.00 );
146
+                }
147
+            }
148
+        }
149
+
150
+        // add total sales, total invoice count, total tax for each period
151
+        $date_format = ( 'day' === $this->groupby ) ? 'Y-m-d' : 'Y-m';
152
+        foreach ( $report_data->invoices as $invoice ) {
153
+            $time = gmdate( $date_format, strtotime( $invoice->post_date ) );
154
+
155
+            if ( ! isset( $period_totals[ $time ] ) ) {
156
+                continue;
157
+            }
158
+
159
+            $period_totals[ $time ]['sales']    = wpinv_round_amount( $invoice->total_sales );
160
+            $period_totals[ $time ]['tax']      = wpinv_round_amount( $invoice->total_tax );
161
+            $period_totals[ $time ]['subtotal'] = wpinv_round_amount( $invoice->subtotal );
162
+            $period_totals[ $time ]['fees']     = wpinv_round_amount( $invoice->total_fees );
163
+
164
+        }
165
+
166
+        foreach ( $report_data->refunds as $invoice ) {
167
+            $time = gmdate( $date_format, strtotime( $invoice->post_date ) );
168
+
169
+            if ( ! isset( $period_totals[ $time ] ) ) {
170
+                continue;
171
+            }
172
+
173
+            $period_totals[ $time ]['refunds']           = wpinv_round_amount( $invoice->total_sales );
174
+            $period_totals[ $time ]['refunded_tax']      = wpinv_round_amount( $invoice->total_tax );
175
+            $period_totals[ $time ]['refunded_subtotal'] = wpinv_round_amount( $invoice->subtotal );
176
+            $period_totals[ $time ]['refunded_fees']     = wpinv_round_amount( $invoice->total_fees );
177
+
178
+        }
179
+
180
+        foreach ( $report_data->invoice_counts as $invoice ) {
181
+            $time = gmdate( $date_format, strtotime( $invoice->post_date ) );
182
+
183
+            if ( isset( $period_totals[ $time ] ) ) {
184
+                $period_totals[ $time ]['invoices']   = (int) $invoice->count;
185
+            }
186
+        }
187
+
188
+        // Add total invoice items for each period.
189
+        foreach ( $report_data->invoice_items as $invoice_item ) {
190
+            $time = ( 'day' === $this->groupby ) ? gmdate( 'Y-m-d', strtotime( $invoice_item->post_date ) ) : gmdate( 'Y-m', strtotime( $invoice_item->post_date ) );
191
+
192
+            if ( isset( $period_totals[ $time ] ) ) {
193
+                $period_totals[ $time ]['items'] = (int) $invoice_item->invoice_item_count;
194
+            }
195
+        }
196
+
197
+        // Add total discount for each period.
198
+        foreach ( $report_data->coupons as $discount ) {
199
+            $time = ( 'day' === $this->groupby ) ? gmdate( 'Y-m-d', strtotime( $discount->post_date ) ) : gmdate( 'Y-m', strtotime( $discount->post_date ) );
200
+
201
+            if ( isset( $period_totals[ $time ] ) ) {
202
+                $period_totals[ $time ]['discount'] = wpinv_round_amount( $discount->discount_amount );
203
+            }
204
+        }
205
+
206
+        // Extra fields.
207
+        foreach ( array_keys( wpinv_get_report_graphs() ) as $key ) {
208
+
209
+            // Abort unprepared.
210
+            if ( ! isset( $report_data->$key ) ) {
211
+                continue;
212
+            }
213
+
214
+            // Abort defaults.
215
+            if ( in_array( $key, array( 'sales', 'refunds', 'tax', 'fees', 'discount', 'invoices', 'items' ) ) ) {
216
+                continue;
217
+            }
218
+
219
+            // Set values.
220
+            foreach ( $report_data->$key as $item ) {
221
+                $time = ( 'day' === $this->groupby ) ? gmdate( 'Y-m-d', strtotime( $item->date ) ) : gmdate( 'Y-m', strtotime( $item->date ) );
222
+
223
+                if ( isset( $period_totals[ $time ] ) ) {
224
+                    $period_totals[ $time ][ $key ] = wpinv_round_amount( $item->val );
225
+                }
226
+            }
227
+
228
+            unset( $report_data->$key );
229
+        }
230
+
231
+        $report_data->totals            = $period_totals;
232
+        $report_data->grouped_by        = $this->groupby;
233
+        $report_data->interval          = max( $this->interval, 1 );
234
+        $report_data->currency          = wpinv_get_currency();
235
+        $report_data->currency_symbol   = wpinv_currency_symbol();
236
+        $report_data->currency_position = wpinv_currency_position();
237
+        $report_data->decimal_places    = wpinv_decimals();
238
+        $report_data->thousands_sep     = wpinv_thousands_separator();
239
+        $report_data->decimals_sep      = wpinv_decimal_separator();
240
+        $report_data->start_date        = gmdate( 'Y-m-d', strtotime( $this->report_range['after'] ) );
241
+        $report_data->end_date          = gmdate( 'Y-m-d', strtotime( $this->report_range['before'] ) );
242
+        $report_data->start_date_locale = getpaid_format_date( gmdate( 'Y-m-d', strtotime( $this->report_range['after'] ) ) );
243
+        $report_data->end_date_locale   = getpaid_format_date( gmdate( 'Y-m-d', strtotime( $this->report_range['before'] ) ) );
244
+        $report_data->decimals_sep      = wpinv_decimal_separator();
245
+
246
+        $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
247
+        $data    = $report_data;
248
+        unset( $data->invoice_counts, $data->invoices, $data->coupons, $data->refunds, $data->invoice_items );
249
+        $data    = $this->add_additional_fields_to_object( (array) $data, $request );
250
+        $data    = $this->filter_response_by_context( $data, $context );
251
+
252
+        // Wrap the data in a response object.
253
+        $response = rest_ensure_response( $data );
254
+        $response->add_links(
255
+            array(
256
+                'about' => array(
257
+                    'href' => rest_url( sprintf( '%s/reports', $this->namespace ) ),
258
+                ),
259
+            )
260
+        );
261
+
262
+        return apply_filters( 'getpaid_rest_prepare_report_sales', $response, $report_data, $request );
263
+    }
264
+
265
+    /**
266
+     * Get report data.
267
+     *
268
+     * @return stdClass
269
+     */
270
+    public function get_report_data() {
271
+        if ( empty( $this->report_data ) ) {
272
+            $this->query_report_data();
273
+        }
274
+        return $this->report_data;
275
+    }
276
+
277
+    /**
278
+     * Get all data needed for this report and store in the class.
279
+     */
280
+    protected function query_report_data() {
281
+
282
+        // Prepare reports.
283
+        $this->report_data = (object) array(
284
+            'invoice_counts' => $this->query_invoice_counts(), //count, post_date
285
+            'coupons'        => $this->query_coupon_counts(), // discount_amount, post_date
286
+            'invoice_items'  => $this->query_item_counts(), // invoice_item_count, post_date
287
+            'refunded_items' => $this->count_refunded_items(), // invoice_item_count, post_date
288
+            'invoices'       => $this->query_invoice_totals(), // total_sales, total_tax, total_discount, total_fees, subtotal, post_date
289
+            'refunds'        => $this->query_refunded_totals(), // total_sales, total_tax, total_discount, total_fees, subtotal, post_date
290
+            'previous_range' => $this->previous_range,
291
+        );
292
+
293
+        // Calculated totals.
294
+        $this->report_data->total_tax          = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_tax' ) ) );
295
+        $this->report_data->total_sales        = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_sales' ) ) );
296
+        $this->report_data->total_discount     = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_discount' ) ) );
297
+        $this->report_data->total_fees         = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_fees' ) ) );
298
+        $this->report_data->subtotal           = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'subtotal' ) ) );
299
+        $this->report_data->net_sales          = wpinv_round_amount( $this->report_data->total_sales - max( 0, $this->report_data->total_tax ) );
300
+        $this->report_data->total_refunded_tax = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_tax' ) ) );
301
+        $this->report_data->total_refunds      = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_sales' ) ) );
302
+        $this->report_data->refunded_discount  = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_discount' ) ) );
303
+        $this->report_data->refunded_fees      = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_fees' ) ) );
304
+        $this->report_data->refunded_subtotal  = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'subtotal' ) ) );
305
+        $this->report_data->net_refunds        = wpinv_round_amount( $this->report_data->total_refunds + max( 0, $this->report_data->total_refunded_tax ) );
306
+
307
+        // Calculate average based on net.
308
+        $this->report_data->average_sales       = wpinv_round_amount( $this->report_data->net_sales / max( $this->interval, 1 ), 2 );
309
+        $this->report_data->average_total_sales = wpinv_round_amount( $this->report_data->total_sales / max( $this->interval, 1 ), 2 );
310
+
311
+        // Total invoices in this period, even if refunded.
312
+        $this->report_data->total_invoices = absint( array_sum( wp_list_pluck( $this->report_data->invoice_counts, 'count' ) ) );
313
+
314
+        // Items invoiced in this period, even if refunded.
315
+        $this->report_data->total_items = absint( array_sum( wp_list_pluck( $this->report_data->invoice_items, 'invoice_item_count' ) ) );
316
+
317
+        // 3rd party filtering of report data
318
+        $this->report_data = apply_filters( 'getpaid_rest_api_filter_report_data', $this->report_data, $this );
319
+    }
320
+
321
+    /**
322
+     * Prepares invoice counts.
323
+     *
324
+     * @return array.
325
+     */
326
+    protected function query_invoice_counts() {
327
+
328
+        return (array) GetPaid_Reports_Helper::get_invoice_report_data(
329
+            array(
330
+                'data'           => array(
331
+                    'ID'        => array(
332
+                        'type'     => 'post_data',
333
+                        'function' => 'COUNT',
334
+                        'name'     => 'count',
335
+                        'distinct' => true,
336
+                    ),
337
+                    'post_date' => array(
338
+                        'type'     => 'post_data',
339
+                        'function' => 'MIN',
340
+                        'name'     => 'post_date',
341
+                    ),
342
+                ),
343
+                'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
344
+                'order_by'       => 'post_date ASC',
345
+                'query_type'     => 'get_results',
346
+                'filter_range'   => $this->report_range,
347
+                'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded', 'wpi-renewal' ),
348
+            )
349
+        );
350
+
351
+    }
352
+
353
+    /**
354
+     * Prepares coupon counts.
355
+     *
356
+     * @return array.
357
+     */
358
+    protected function query_coupon_counts() {
359
+
360
+        return (array) GetPaid_Reports_Helper::get_invoice_report_data(
361
+            array(
362
+                'data'           => array(
363
+                    'discount'  => array(
364
+                        'type'     => 'invoice_data',
365
+                        'function' => 'SUM',
366
+                        'name'     => 'discount_amount',
367
+                    ),
368
+                    'post_date' => array(
369
+                        'type'     => 'post_data',
370
+                        'function' => 'MIN',
371
+                        'name'     => 'post_date',
372
+                    ),
373
+                ),
374
+                'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
375
+                'order_by'       => 'post_date ASC',
376
+                'query_type'     => 'get_results',
377
+                'filter_range'   => $this->report_range,
378
+                'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded', 'wpi-renewal' ),
379
+            )
380
+        );
381
+
382
+    }
383
+
384
+    /**
385
+     * Prepares item counts.
386
+     *
387
+     * @return array.
388
+     */
389
+    protected function query_item_counts() {
390
+
391
+        return (array) GetPaid_Reports_Helper::get_invoice_report_data(
392
+            array(
393
+                'data'           => array(
394
+                    'quantity'  => array(
395
+                        'type'     => 'invoice_item',
396
+                        'function' => 'SUM',
397
+                        'name'     => 'invoice_item_count',
398
+                    ),
399
+                    'post_date' => array(
400
+                        'type'     => 'post_data',
401
+                        'function' => 'MIN',
402
+                        'name'     => 'post_date',
403
+                    ),
404
+                ),
405
+                'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
406
+                'order_by'       => 'post_date ASC',
407
+                'query_type'     => 'get_results',
408
+                'filter_range'   => $this->report_range,
409
+                'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded', 'wpi-renewal' ),
410
+            )
411
+        );
412
+
413
+    }
414
+
415
+    /**
416
+     * Prepares refunded item counts.
417
+     *
418
+     * @return array.
419
+     */
420
+    protected function count_refunded_items() {
421
+
422
+        return (int) GetPaid_Reports_Helper::get_invoice_report_data(
423
+            array(
424
+                'data'           => array(
425
+                    'quantity' => array(
426
+                        'type'     => 'invoice_item',
427
+                        'function' => 'SUM',
428
+                        'name'     => 'invoice_item_count',
429
+                    ),
430
+                ),
431
+                'query_type'     => 'get_var',
432
+                'filter_range'   => $this->report_range,
433
+                'invoice_status' => array( 'wpi-refunded' ),
434
+            )
435
+        );
436
+
437
+    }
438
+
439
+    /**
440
+     * Prepares daily invoice totals.
441
+     *
442
+     * @return array.
443
+     */
444
+    protected function query_invoice_totals() {
445
+
446
+        return (array) GetPaid_Reports_Helper::get_invoice_report_data(
447
+            array(
448
+                'data'           => array(
449
+                    'total'      => array(
450
+                        'type'     => 'invoice_data',
451
+                        'function' => 'SUM',
452
+                        'name'     => 'total_sales',
453
+                    ),
454
+                    'tax'        => array(
455
+                        'type'     => 'invoice_data',
456
+                        'function' => 'SUM',
457
+                        'name'     => 'total_tax',
458
+                    ),
459
+                    'discount'   => array(
460
+                        'type'     => 'invoice_data',
461
+                        'function' => 'SUM',
462
+                        'name'     => 'total_discount',
463
+                    ),
464
+                    'fees_total' => array(
465
+                        'type'     => 'invoice_data',
466
+                        'function' => 'SUM',
467
+                        'name'     => 'total_fees',
468
+                    ),
469
+                    'subtotal'   => array(
470
+                        'type'     => 'invoice_data',
471
+                        'function' => 'SUM',
472
+                        'name'     => 'subtotal',
473
+                    ),
474
+                    'post_date'  => array(
475
+                        'type'     => 'post_data',
476
+                        'function' => '',
477
+                        'name'     => 'post_date',
478
+                    ),
479
+                ),
480
+                'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
481
+                'order_by'       => 'post_date ASC',
482
+                'query_type'     => 'get_results',
483
+                'filter_range'   => $this->report_range,
484
+                'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-renewal' ),
485
+            )
486
+        );
487
+
488
+    }
489
+
490
+    /**
491
+     * Prepares daily invoice totals.
492
+     *
493
+     * @return array.
494
+     */
495
+    protected function query_refunded_totals() {
496
+
497
+        return (array) GetPaid_Reports_Helper::get_invoice_report_data(
498
+            array(
499
+                'data'           => array(
500
+                    'total'      => array(
501
+                        'type'     => 'invoice_data',
502
+                        'function' => 'SUM',
503
+                        'name'     => 'total_sales',
504
+                    ),
505
+                    'tax'        => array(
506
+                        'type'     => 'invoice_data',
507
+                        'function' => 'SUM',
508
+                        'name'     => 'total_tax',
509
+                    ),
510
+                    'discount'   => array(
511
+                        'type'     => 'invoice_data',
512
+                        'function' => 'SUM',
513
+                        'name'     => 'total_discount',
514
+                    ),
515
+                    'fees_total' => array(
516
+                        'type'     => 'invoice_data',
517
+                        'function' => 'SUM',
518
+                        'name'     => 'total_fees',
519
+                    ),
520
+                    'subtotal'   => array(
521
+                        'type'     => 'invoice_data',
522
+                        'function' => 'SUM',
523
+                        'name'     => 'subtotal',
524
+                    ),
525
+                    'post_date'  => array(
526
+                        'type'     => 'post_data',
527
+                        'function' => '',
528
+                        'name'     => 'post_date',
529
+                    ),
530
+                ),
531
+                'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
532
+                'order_by'       => 'post_date ASC',
533
+                'query_type'     => 'get_results',
534
+                'filter_range'   => $this->report_range,
535
+                'invoice_status' => array( 'wpi-refunded' ),
536
+            )
537
+        );
538
+
539
+    }
540
+
541
+    /**
542
+     * Get the Report's schema, conforming to JSON Schema.
543
+     *
544
+     * @return array
545
+     */
546
+    public function get_item_schema() {
547
+
548
+        $schema = array(
549
+            '$schema'    => 'http://json-schema.org/draft-04/schema#',
550
+            'title'      => 'sales_report',
551
+            'type'       => 'object',
552
+            'properties' => array(
553
+                'total_sales'         => array(
554
+                    'description' => __( 'Gross sales in the period.', 'invoicing' ),
555
+                    'type'        => 'string',
556
+                    'context'     => array( 'view' ),
557
+                    'readonly'    => true,
558
+                ),
559
+                'net_sales'           => array(
560
+                    'description' => __( 'Net sales in the period.', 'invoicing' ),
561
+                    'type'        => 'string',
562
+                    'context'     => array( 'view' ),
563
+                    'readonly'    => true,
564
+                ),
565
+                'average_sales'       => array(
566
+                    'description' => __( 'Average net daily sales.', 'invoicing' ),
567
+                    'type'        => 'string',
568
+                    'context'     => array( 'view' ),
569
+                    'readonly'    => true,
570
+                ),
571
+                'average_total_sales' => array(
572
+                    'description' => __( 'Average gross daily sales.', 'invoicing' ),
573
+                    'type'        => 'string',
574
+                    'context'     => array( 'view' ),
575
+                    'readonly'    => true,
576
+                ),
577
+                'total_invoices'      => array(
578
+                    'description' => __( 'Number of paid invoices.', 'invoicing' ),
579
+                    'type'        => 'integer',
580
+                    'context'     => array( 'view' ),
581
+                    'readonly'    => true,
582
+                ),
583
+                'total_items'         => array(
584
+                    'description' => __( 'Number of items purchased.', 'invoicing' ),
585
+                    'type'        => 'integer',
586
+                    'context'     => array( 'view' ),
587
+                    'readonly'    => true,
588
+                ),
589
+                'refunded_items'      => array(
590
+                    'description' => __( 'Number of items refunded.', 'invoicing' ),
591
+                    'type'        => 'integer',
592
+                    'context'     => array( 'view' ),
593
+                    'readonly'    => true,
594
+                ),
595
+                'total_tax'           => array(
596
+                    'description' => __( 'Total charged for taxes.', 'invoicing' ),
597
+                    'type'        => 'string',
598
+                    'context'     => array( 'view' ),
599
+                    'readonly'    => true,
600
+                ),
601
+                'total_refunded_tax'  => array(
602
+                    'description' => __( 'Total refunded for taxes.', 'invoicing' ),
603
+                    'type'        => 'string',
604
+                    'context'     => array( 'view' ),
605
+                    'readonly'    => true,
606
+                ),
607
+                'total_fees'          => array(
608
+                    'description' => __( 'Total fees charged.', 'invoicing' ),
609
+                    'type'        => 'string',
610
+                    'context'     => array( 'view' ),
611
+                    'readonly'    => true,
612
+                ),
613
+                'total_refunds'       => array(
614
+                    'description' => __( 'Total of refunded invoices.', 'invoicing' ),
615
+                    'type'        => 'integer',
616
+                    'context'     => array( 'view' ),
617
+                    'readonly'    => true,
618
+                ),
619
+                'net_refunds'         => array(
620
+                    'description' => __( 'Net of refunded invoices.', 'invoicing' ),
621
+                    'type'        => 'integer',
622
+                    'context'     => array( 'view' ),
623
+                    'readonly'    => true,
624
+                ),
625
+                'total_discount'      => array(
626
+                    'description' => __( 'Total of discounts used.', 'invoicing' ),
627
+                    'type'        => 'integer',
628
+                    'context'     => array( 'view' ),
629
+                    'readonly'    => true,
630
+                ),
631
+                'totals'              => array(
632
+                    'description' => __( 'Totals.', 'invoicing' ),
633
+                    'type'        => 'array',
634
+                    'items'       => array(
635
+                        'type' => 'array',
636
+                    ),
637
+                    'context'     => array( 'view' ),
638
+                    'readonly'    => true,
639
+                ),
640
+                'interval'            => array(
641
+                    'description' => __( 'Number of months/days in the report period.', 'invoicing' ),
642
+                    'type'        => 'integer',
643
+                    'context'     => array( 'view' ),
644
+                    'readonly'    => true,
645
+                ),
646
+                'previous_range'      => array(
647
+                    'description' => __( 'The previous report period.', 'invoicing' ),
648
+                    'type'        => 'array',
649
+                    'items'       => array(
650
+                        'type' => 'string',
651
+                    ),
652
+                    'context'     => array( 'view' ),
653
+                    'readonly'    => true,
654
+                ),
655
+                'grouped_by'          => array(
656
+                    'description' => __( 'The period used to group the totals.', 'invoicing' ),
657
+                    'type'        => 'string',
658
+                    'context'     => array( 'view' ),
659
+                    'enum'        => array( 'day', 'month' ),
660
+                    'readonly'    => true,
661
+                ),
662
+                'currency'            => array(
663
+                    'description' => __( 'The default store currency.', 'invoicing' ),
664
+                    'type'        => 'string',
665
+                    'context'     => array( 'view' ),
666
+                    'readonly'    => true,
667
+                ),
668
+                'currency_symbol'     => array(
669
+                    'description' => __( 'The default store currency symbol.', 'invoicing' ),
670
+                    'type'        => 'string',
671
+                    'context'     => array( 'view' ),
672
+                    'readonly'    => true,
673
+                ),
674
+                'currency_position'   => array(
675
+                    'description' => __( 'The default store currency position.', 'invoicing' ),
676
+                    'type'        => 'string',
677
+                    'context'     => array( 'view' ),
678
+                    'readonly'    => true,
679
+                ),
680
+                'decimal_places'      => array(
681
+                    'description' => __( 'The default store decimal places.', 'invoicing' ),
682
+                    'type'        => 'string',
683
+                    'context'     => array( 'view' ),
684
+                    'readonly'    => true,
685
+                ),
686
+                'thousands_sep'       => array(
687
+                    'description' => __( 'The default store thousands separator.', 'invoicing' ),
688
+                    'type'        => 'string',
689
+                    'context'     => array( 'view' ),
690
+                    'readonly'    => true,
691
+                ),
692
+                'decimals_sep'        => array(
693
+                    'description' => __( 'The default store decimals separator.', 'invoicing' ),
694
+                    'type'        => 'string',
695
+                    'context'     => array( 'view' ),
696
+                    'readonly'    => true,
697
+                ),
698
+            ),
699
+        );
700
+
701
+        return $this->add_additional_fields_schema( $schema );
702
+
703
+    }
704 704
 
705 705
 }
Please login to merge, or discard this patch.
Spacing   +154 added lines, -154 removed lines patch added patch discarded remove patch
@@ -9,7 +9,7 @@  discard block
 block discarded – undo
9 9
  * @since   2.0.0
10 10
  */
11 11
 
12
-defined( 'ABSPATH' ) || exit;
12
+defined('ABSPATH') || exit;
13 13
 
14 14
 /**
15 15
  * GetPaid REST reports controller class.
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
 	 *
47 47
 	 * @see register_rest_route()
48 48
 	 */
49
-	public function register_namespace_routes( $namespace ) {
49
+	public function register_namespace_routes($namespace) {
50 50
 
51 51
 		// Get sales report.
52 52
 		register_rest_route(
@@ -55,11 +55,11 @@  discard block
 block discarded – undo
55 55
 			array(
56 56
 				array(
57 57
 					'methods'             => WP_REST_Server::READABLE,
58
-					'callback'            => array( $this, 'get_items' ),
59
-					'permission_callback' => array( $this, 'get_items_permissions_check' ),
58
+					'callback'            => array($this, 'get_items'),
59
+					'permission_callback' => array($this, 'get_items_permissions_check'),
60 60
 					'args'                => $this->get_collection_params(),
61 61
 				),
62
-				'schema' => array( $this, 'get_public_item_schema' ),
62
+				'schema' => array($this, 'get_public_item_schema'),
63 63
 			)
64 64
 		);
65 65
 
@@ -72,10 +72,10 @@  discard block
 block discarded – undo
72 72
 	 * @param WP_REST_Request $request Full data about the request.
73 73
 	 * @return WP_Error|boolean
74 74
 	 */
75
-	public function get_items_permissions_check( $request ) {
75
+	public function get_items_permissions_check($request) {
76 76
 
77
-		if ( ! wpinv_current_user_can_manage_invoicing() ) {
78
-			return new WP_Error( 'rest_cannot_view', __( 'Sorry, you cannot list resources.', 'invoicing' ), array( 'status' => rest_authorization_required_code() ) );
77
+		if (!wpinv_current_user_can_manage_invoicing()) {
78
+			return new WP_Error('rest_cannot_view', __('Sorry, you cannot list resources.', 'invoicing'), array('status' => rest_authorization_required_code()));
79 79
 		}
80 80
 
81 81
 		return true;
@@ -87,12 +87,12 @@  discard block
 block discarded – undo
87 87
 	 * @param WP_REST_Request $request
88 88
 	 * @return array|WP_Error
89 89
 	 */
90
-	public function get_items( $request ) {
90
+	public function get_items($request) {
91 91
 		$data   = array();
92
-		$item   = $this->prepare_item_for_response( null, $request );
93
-		$data[] = $this->prepare_response_for_collection( $item );
92
+		$item   = $this->prepare_item_for_response(null, $request);
93
+		$data[] = $this->prepare_response_for_collection($item);
94 94
 
95
-		return rest_ensure_response( $data );
95
+		return rest_ensure_response($data);
96 96
 	}
97 97
 
98 98
 	/**
@@ -102,164 +102,164 @@  discard block
 block discarded – undo
102 102
 	 * @param WP_REST_Request $request Request object.
103 103
 	 * @return WP_REST_Response $response Response data.
104 104
 	 */
105
-	public function prepare_item_for_response( $_, $request ) {
105
+	public function prepare_item_for_response($_, $request) {
106 106
 
107 107
 		// Set report range.
108
-		$this->report_range = $this->get_date_range( $request );
108
+		$this->report_range = $this->get_date_range($request);
109 109
 
110 110
 		$report_data     = $this->get_report_data();
111 111
 		$period_totals   = array();
112 112
 
113 113
 		// Setup period totals by ensuring each period in the interval has data.
114
-		$start_date      = strtotime( $this->report_range['after'] );
114
+		$start_date      = strtotime($this->report_range['after']);
115 115
 
116
-		if ( 'month' === $this->groupby ) {
117
-			$start_date      = strtotime( gmdate( 'Y-m-01', $start_date ) );
116
+		if ('month' === $this->groupby) {
117
+			$start_date = strtotime(gmdate('Y-m-01', $start_date));
118 118
 		}
119 119
 
120
-		for ( $i = 0; $i < $this->interval; $i++ ) {
120
+		for ($i = 0; $i < $this->interval; $i++) {
121 121
 
122
-			switch ( $this->groupby ) {
122
+			switch ($this->groupby) {
123 123
 				case 'day':
124
-					$time = gmdate( 'Y-m-d', strtotime( "+{$i} DAY", $start_date ) );
124
+					$time = gmdate('Y-m-d', strtotime("+{$i} DAY", $start_date));
125 125
 					break;
126 126
 				default:
127
-					$time = gmdate( 'Y-m', strtotime( "+{$i} MONTH", $start_date ) );
127
+					$time = gmdate('Y-m', strtotime("+{$i} MONTH", $start_date));
128 128
 					break;
129 129
 			}
130 130
 
131 131
 			// Set the defaults for each period.
132
-			$period_totals[ $time ] = array(
132
+			$period_totals[$time] = array(
133 133
 				'invoices'          => 0,
134 134
 				'items'             => 0,
135 135
 				'refunded_items'    => 0,
136
-				'refunded_tax'      => wpinv_round_amount( 0.00 ),
137
-				'subtotal'          => wpinv_round_amount( 0.00 ),
138
-				'refunded_subtotal' => wpinv_round_amount( 0.00 ),
139
-				'refunded_fees'     => wpinv_round_amount( 0.00 ),
140
-				'discount'          => wpinv_round_amount( 0.00 ),
136
+				'refunded_tax'      => wpinv_round_amount(0.00),
137
+				'subtotal'          => wpinv_round_amount(0.00),
138
+				'refunded_subtotal' => wpinv_round_amount(0.00),
139
+				'refunded_fees'     => wpinv_round_amount(0.00),
140
+				'discount'          => wpinv_round_amount(0.00),
141 141
 			);
142 142
 
143
-			foreach ( array_keys( wpinv_get_report_graphs() ) as $key ) {
144
-				if ( ! isset( $period_totals[ $time ][ $key ] ) ) {
145
-					$period_totals[ $time ][ $key ] = wpinv_round_amount( 0.00 );
143
+			foreach (array_keys(wpinv_get_report_graphs()) as $key) {
144
+				if (!isset($period_totals[$time][$key])) {
145
+					$period_totals[$time][$key] = wpinv_round_amount(0.00);
146 146
 				}
147 147
 			}
148 148
 		}
149 149
 
150 150
 		// add total sales, total invoice count, total tax for each period
151
-		$date_format = ( 'day' === $this->groupby ) ? 'Y-m-d' : 'Y-m';
152
-		foreach ( $report_data->invoices as $invoice ) {
153
-			$time = gmdate( $date_format, strtotime( $invoice->post_date ) );
151
+		$date_format = ('day' === $this->groupby) ? 'Y-m-d' : 'Y-m';
152
+		foreach ($report_data->invoices as $invoice) {
153
+			$time = gmdate($date_format, strtotime($invoice->post_date));
154 154
 
155
-			if ( ! isset( $period_totals[ $time ] ) ) {
155
+			if (!isset($period_totals[$time])) {
156 156
 				continue;
157 157
 			}
158 158
 
159
-			$period_totals[ $time ]['sales']    = wpinv_round_amount( $invoice->total_sales );
160
-			$period_totals[ $time ]['tax']      = wpinv_round_amount( $invoice->total_tax );
161
-			$period_totals[ $time ]['subtotal'] = wpinv_round_amount( $invoice->subtotal );
162
-			$period_totals[ $time ]['fees']     = wpinv_round_amount( $invoice->total_fees );
159
+			$period_totals[$time]['sales']    = wpinv_round_amount($invoice->total_sales);
160
+			$period_totals[$time]['tax']      = wpinv_round_amount($invoice->total_tax);
161
+			$period_totals[$time]['subtotal'] = wpinv_round_amount($invoice->subtotal);
162
+			$period_totals[$time]['fees']     = wpinv_round_amount($invoice->total_fees);
163 163
 
164 164
 		}
165 165
 
166
-		foreach ( $report_data->refunds as $invoice ) {
167
-			$time = gmdate( $date_format, strtotime( $invoice->post_date ) );
166
+		foreach ($report_data->refunds as $invoice) {
167
+			$time = gmdate($date_format, strtotime($invoice->post_date));
168 168
 
169
-			if ( ! isset( $period_totals[ $time ] ) ) {
169
+			if (!isset($period_totals[$time])) {
170 170
 				continue;
171 171
 			}
172 172
 
173
-			$period_totals[ $time ]['refunds']           = wpinv_round_amount( $invoice->total_sales );
174
-			$period_totals[ $time ]['refunded_tax']      = wpinv_round_amount( $invoice->total_tax );
175
-			$period_totals[ $time ]['refunded_subtotal'] = wpinv_round_amount( $invoice->subtotal );
176
-			$period_totals[ $time ]['refunded_fees']     = wpinv_round_amount( $invoice->total_fees );
173
+			$period_totals[$time]['refunds']           = wpinv_round_amount($invoice->total_sales);
174
+			$period_totals[$time]['refunded_tax']      = wpinv_round_amount($invoice->total_tax);
175
+			$period_totals[$time]['refunded_subtotal'] = wpinv_round_amount($invoice->subtotal);
176
+			$period_totals[$time]['refunded_fees']     = wpinv_round_amount($invoice->total_fees);
177 177
 
178 178
 		}
179 179
 
180
-		foreach ( $report_data->invoice_counts as $invoice ) {
181
-			$time = gmdate( $date_format, strtotime( $invoice->post_date ) );
180
+		foreach ($report_data->invoice_counts as $invoice) {
181
+			$time = gmdate($date_format, strtotime($invoice->post_date));
182 182
 
183
-			if ( isset( $period_totals[ $time ] ) ) {
184
-				$period_totals[ $time ]['invoices']   = (int) $invoice->count;
183
+			if (isset($period_totals[$time])) {
184
+				$period_totals[$time]['invoices'] = (int) $invoice->count;
185 185
 			}
186 186
 		}
187 187
 
188 188
 		// Add total invoice items for each period.
189
-		foreach ( $report_data->invoice_items as $invoice_item ) {
190
-			$time = ( 'day' === $this->groupby ) ? gmdate( 'Y-m-d', strtotime( $invoice_item->post_date ) ) : gmdate( 'Y-m', strtotime( $invoice_item->post_date ) );
189
+		foreach ($report_data->invoice_items as $invoice_item) {
190
+			$time = ('day' === $this->groupby) ? gmdate('Y-m-d', strtotime($invoice_item->post_date)) : gmdate('Y-m', strtotime($invoice_item->post_date));
191 191
 
192
-			if ( isset( $period_totals[ $time ] ) ) {
193
-				$period_totals[ $time ]['items'] = (int) $invoice_item->invoice_item_count;
192
+			if (isset($period_totals[$time])) {
193
+				$period_totals[$time]['items'] = (int) $invoice_item->invoice_item_count;
194 194
 			}
195 195
 		}
196 196
 
197 197
 		// Add total discount for each period.
198
-		foreach ( $report_data->coupons as $discount ) {
199
-			$time = ( 'day' === $this->groupby ) ? gmdate( 'Y-m-d', strtotime( $discount->post_date ) ) : gmdate( 'Y-m', strtotime( $discount->post_date ) );
198
+		foreach ($report_data->coupons as $discount) {
199
+			$time = ('day' === $this->groupby) ? gmdate('Y-m-d', strtotime($discount->post_date)) : gmdate('Y-m', strtotime($discount->post_date));
200 200
 
201
-			if ( isset( $period_totals[ $time ] ) ) {
202
-				$period_totals[ $time ]['discount'] = wpinv_round_amount( $discount->discount_amount );
201
+			if (isset($period_totals[$time])) {
202
+				$period_totals[$time]['discount'] = wpinv_round_amount($discount->discount_amount);
203 203
 			}
204 204
 		}
205 205
 
206 206
 		// Extra fields.
207
-		foreach ( array_keys( wpinv_get_report_graphs() ) as $key ) {
207
+		foreach (array_keys(wpinv_get_report_graphs()) as $key) {
208 208
 
209 209
 			// Abort unprepared.
210
-			if ( ! isset( $report_data->$key ) ) {
210
+			if (!isset($report_data->$key)) {
211 211
 				continue;
212 212
 			}
213 213
 
214 214
 			// Abort defaults.
215
-			if ( in_array( $key, array( 'sales', 'refunds', 'tax', 'fees', 'discount', 'invoices', 'items' ) ) ) {
215
+			if (in_array($key, array('sales', 'refunds', 'tax', 'fees', 'discount', 'invoices', 'items'))) {
216 216
 				continue;
217 217
 			}
218 218
 
219 219
 			// Set values.
220
-			foreach ( $report_data->$key as $item ) {
221
-				$time = ( 'day' === $this->groupby ) ? gmdate( 'Y-m-d', strtotime( $item->date ) ) : gmdate( 'Y-m', strtotime( $item->date ) );
220
+			foreach ($report_data->$key as $item) {
221
+				$time = ('day' === $this->groupby) ? gmdate('Y-m-d', strtotime($item->date)) : gmdate('Y-m', strtotime($item->date));
222 222
 
223
-				if ( isset( $period_totals[ $time ] ) ) {
224
-					$period_totals[ $time ][ $key ] = wpinv_round_amount( $item->val );
223
+				if (isset($period_totals[$time])) {
224
+					$period_totals[$time][$key] = wpinv_round_amount($item->val);
225 225
 				}
226 226
 			}
227 227
 
228
-			unset( $report_data->$key );
228
+			unset($report_data->$key);
229 229
 		}
230 230
 
231 231
 		$report_data->totals            = $period_totals;
232 232
 		$report_data->grouped_by        = $this->groupby;
233
-		$report_data->interval          = max( $this->interval, 1 );
233
+		$report_data->interval          = max($this->interval, 1);
234 234
 		$report_data->currency          = wpinv_get_currency();
235 235
 		$report_data->currency_symbol   = wpinv_currency_symbol();
236 236
 		$report_data->currency_position = wpinv_currency_position();
237 237
 		$report_data->decimal_places    = wpinv_decimals();
238 238
 		$report_data->thousands_sep     = wpinv_thousands_separator();
239 239
 		$report_data->decimals_sep      = wpinv_decimal_separator();
240
-		$report_data->start_date        = gmdate( 'Y-m-d', strtotime( $this->report_range['after'] ) );
241
-		$report_data->end_date          = gmdate( 'Y-m-d', strtotime( $this->report_range['before'] ) );
242
-		$report_data->start_date_locale = getpaid_format_date( gmdate( 'Y-m-d', strtotime( $this->report_range['after'] ) ) );
243
-		$report_data->end_date_locale   = getpaid_format_date( gmdate( 'Y-m-d', strtotime( $this->report_range['before'] ) ) );
240
+		$report_data->start_date        = gmdate('Y-m-d', strtotime($this->report_range['after']));
241
+		$report_data->end_date          = gmdate('Y-m-d', strtotime($this->report_range['before']));
242
+		$report_data->start_date_locale = getpaid_format_date(gmdate('Y-m-d', strtotime($this->report_range['after'])));
243
+		$report_data->end_date_locale   = getpaid_format_date(gmdate('Y-m-d', strtotime($this->report_range['before'])));
244 244
 		$report_data->decimals_sep      = wpinv_decimal_separator();
245 245
 
246
-		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
246
+		$context = !empty($request['context']) ? $request['context'] : 'view';
247 247
 		$data    = $report_data;
248
-		unset( $data->invoice_counts, $data->invoices, $data->coupons, $data->refunds, $data->invoice_items );
249
-		$data    = $this->add_additional_fields_to_object( (array) $data, $request );
250
-		$data    = $this->filter_response_by_context( $data, $context );
248
+		unset($data->invoice_counts, $data->invoices, $data->coupons, $data->refunds, $data->invoice_items);
249
+		$data    = $this->add_additional_fields_to_object((array) $data, $request);
250
+		$data    = $this->filter_response_by_context($data, $context);
251 251
 
252 252
 		// Wrap the data in a response object.
253
-		$response = rest_ensure_response( $data );
253
+		$response = rest_ensure_response($data);
254 254
 		$response->add_links(
255 255
             array(
256 256
 				'about' => array(
257
-					'href' => rest_url( sprintf( '%s/reports', $this->namespace ) ),
257
+					'href' => rest_url(sprintf('%s/reports', $this->namespace)),
258 258
 				),
259 259
             )
260 260
         );
261 261
 
262
-		return apply_filters( 'getpaid_rest_prepare_report_sales', $response, $report_data, $request );
262
+		return apply_filters('getpaid_rest_prepare_report_sales', $response, $report_data, $request);
263 263
 	}
264 264
 
265 265
 	/**
@@ -268,7 +268,7 @@  discard block
 block discarded – undo
268 268
 	 * @return stdClass
269 269
 	 */
270 270
 	public function get_report_data() {
271
-		if ( empty( $this->report_data ) ) {
271
+		if (empty($this->report_data)) {
272 272
 			$this->query_report_data();
273 273
 		}
274 274
 		return $this->report_data;
@@ -291,31 +291,31 @@  discard block
 block discarded – undo
291 291
 		);
292 292
 
293 293
 		// Calculated totals.
294
-		$this->report_data->total_tax          = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_tax' ) ) );
295
-		$this->report_data->total_sales        = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_sales' ) ) );
296
-		$this->report_data->total_discount     = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_discount' ) ) );
297
-		$this->report_data->total_fees         = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'total_fees' ) ) );
298
-		$this->report_data->subtotal           = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->invoices, 'subtotal' ) ) );
299
-		$this->report_data->net_sales          = wpinv_round_amount( $this->report_data->total_sales - max( 0, $this->report_data->total_tax ) );
300
-		$this->report_data->total_refunded_tax = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_tax' ) ) );
301
-		$this->report_data->total_refunds      = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_sales' ) ) );
302
-		$this->report_data->refunded_discount  = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_discount' ) ) );
303
-		$this->report_data->refunded_fees      = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'total_fees' ) ) );
304
-		$this->report_data->refunded_subtotal  = wpinv_round_amount( array_sum( wp_list_pluck( $this->report_data->refunds, 'subtotal' ) ) );
305
-		$this->report_data->net_refunds        = wpinv_round_amount( $this->report_data->total_refunds + max( 0, $this->report_data->total_refunded_tax ) );
294
+		$this->report_data->total_tax          = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->invoices, 'total_tax')));
295
+		$this->report_data->total_sales        = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->invoices, 'total_sales')));
296
+		$this->report_data->total_discount     = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->invoices, 'total_discount')));
297
+		$this->report_data->total_fees         = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->invoices, 'total_fees')));
298
+		$this->report_data->subtotal           = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->invoices, 'subtotal')));
299
+		$this->report_data->net_sales          = wpinv_round_amount($this->report_data->total_sales - max(0, $this->report_data->total_tax));
300
+		$this->report_data->total_refunded_tax = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->refunds, 'total_tax')));
301
+		$this->report_data->total_refunds      = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->refunds, 'total_sales')));
302
+		$this->report_data->refunded_discount  = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->refunds, 'total_discount')));
303
+		$this->report_data->refunded_fees      = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->refunds, 'total_fees')));
304
+		$this->report_data->refunded_subtotal  = wpinv_round_amount(array_sum(wp_list_pluck($this->report_data->refunds, 'subtotal')));
305
+		$this->report_data->net_refunds        = wpinv_round_amount($this->report_data->total_refunds + max(0, $this->report_data->total_refunded_tax));
306 306
 
307 307
 		// Calculate average based on net.
308
-		$this->report_data->average_sales       = wpinv_round_amount( $this->report_data->net_sales / max( $this->interval, 1 ), 2 );
309
-		$this->report_data->average_total_sales = wpinv_round_amount( $this->report_data->total_sales / max( $this->interval, 1 ), 2 );
308
+		$this->report_data->average_sales       = wpinv_round_amount($this->report_data->net_sales / max($this->interval, 1), 2);
309
+		$this->report_data->average_total_sales = wpinv_round_amount($this->report_data->total_sales / max($this->interval, 1), 2);
310 310
 
311 311
 		// Total invoices in this period, even if refunded.
312
-		$this->report_data->total_invoices = absint( array_sum( wp_list_pluck( $this->report_data->invoice_counts, 'count' ) ) );
312
+		$this->report_data->total_invoices = absint(array_sum(wp_list_pluck($this->report_data->invoice_counts, 'count')));
313 313
 
314 314
 		// Items invoiced in this period, even if refunded.
315
-		$this->report_data->total_items = absint( array_sum( wp_list_pluck( $this->report_data->invoice_items, 'invoice_item_count' ) ) );
315
+		$this->report_data->total_items = absint(array_sum(wp_list_pluck($this->report_data->invoice_items, 'invoice_item_count')));
316 316
 
317 317
 		// 3rd party filtering of report data
318
-		$this->report_data = apply_filters( 'getpaid_rest_api_filter_report_data', $this->report_data, $this );
318
+		$this->report_data = apply_filters('getpaid_rest_api_filter_report_data', $this->report_data, $this);
319 319
 	}
320 320
 
321 321
 	/**
@@ -340,11 +340,11 @@  discard block
 block discarded – undo
340 340
 						'name'     => 'post_date',
341 341
 					),
342 342
 				),
343
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
343
+				'group_by'       => $this->get_group_by_sql('posts.post_date'),
344 344
 				'order_by'       => 'post_date ASC',
345 345
 				'query_type'     => 'get_results',
346 346
 				'filter_range'   => $this->report_range,
347
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded', 'wpi-renewal' ),
347
+				'invoice_status' => array('publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded', 'wpi-renewal'),
348 348
 			)
349 349
 		);
350 350
 
@@ -371,11 +371,11 @@  discard block
 block discarded – undo
371 371
 						'name'     => 'post_date',
372 372
 					),
373 373
 				),
374
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
374
+				'group_by'       => $this->get_group_by_sql('posts.post_date'),
375 375
 				'order_by'       => 'post_date ASC',
376 376
 				'query_type'     => 'get_results',
377 377
 				'filter_range'   => $this->report_range,
378
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded', 'wpi-renewal' ),
378
+				'invoice_status' => array('publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded', 'wpi-renewal'),
379 379
 			)
380 380
 		);
381 381
 
@@ -402,11 +402,11 @@  discard block
 block discarded – undo
402 402
 						'name'     => 'post_date',
403 403
 					),
404 404
 				),
405
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
405
+				'group_by'       => $this->get_group_by_sql('posts.post_date'),
406 406
 				'order_by'       => 'post_date ASC',
407 407
 				'query_type'     => 'get_results',
408 408
 				'filter_range'   => $this->report_range,
409
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded', 'wpi-renewal' ),
409
+				'invoice_status' => array('publish', 'wpi-processing', 'wpi-onhold', 'wpi-refunded', 'wpi-renewal'),
410 410
 			)
411 411
 		);
412 412
 
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 				),
431 431
 				'query_type'     => 'get_var',
432 432
 				'filter_range'   => $this->report_range,
433
-				'invoice_status' => array( 'wpi-refunded' ),
433
+				'invoice_status' => array('wpi-refunded'),
434 434
 			)
435 435
 		);
436 436
 
@@ -477,11 +477,11 @@  discard block
 block discarded – undo
477 477
 						'name'     => 'post_date',
478 478
 					),
479 479
 				),
480
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
480
+				'group_by'       => $this->get_group_by_sql('posts.post_date'),
481 481
 				'order_by'       => 'post_date ASC',
482 482
 				'query_type'     => 'get_results',
483 483
 				'filter_range'   => $this->report_range,
484
-				'invoice_status' => array( 'publish', 'wpi-processing', 'wpi-onhold', 'wpi-renewal' ),
484
+				'invoice_status' => array('publish', 'wpi-processing', 'wpi-onhold', 'wpi-renewal'),
485 485
 			)
486 486
 		);
487 487
 
@@ -528,11 +528,11 @@  discard block
 block discarded – undo
528 528
 						'name'     => 'post_date',
529 529
 					),
530 530
 				),
531
-				'group_by'       => $this->get_group_by_sql( 'posts.post_date' ),
531
+				'group_by'       => $this->get_group_by_sql('posts.post_date'),
532 532
 				'order_by'       => 'post_date ASC',
533 533
 				'query_type'     => 'get_results',
534 534
 				'filter_range'   => $this->report_range,
535
-				'invoice_status' => array( 'wpi-refunded' ),
535
+				'invoice_status' => array('wpi-refunded'),
536 536
 			)
537 537
 		);
538 538
 
@@ -551,154 +551,154 @@  discard block
 block discarded – undo
551 551
 			'type'       => 'object',
552 552
 			'properties' => array(
553 553
 				'total_sales'         => array(
554
-					'description' => __( 'Gross sales in the period.', 'invoicing' ),
554
+					'description' => __('Gross sales in the period.', 'invoicing'),
555 555
 					'type'        => 'string',
556
-					'context'     => array( 'view' ),
556
+					'context'     => array('view'),
557 557
 					'readonly'    => true,
558 558
 				),
559 559
 				'net_sales'           => array(
560
-					'description' => __( 'Net sales in the period.', 'invoicing' ),
560
+					'description' => __('Net sales in the period.', 'invoicing'),
561 561
 					'type'        => 'string',
562
-					'context'     => array( 'view' ),
562
+					'context'     => array('view'),
563 563
 					'readonly'    => true,
564 564
 				),
565 565
 				'average_sales'       => array(
566
-					'description' => __( 'Average net daily sales.', 'invoicing' ),
566
+					'description' => __('Average net daily sales.', 'invoicing'),
567 567
 					'type'        => 'string',
568
-					'context'     => array( 'view' ),
568
+					'context'     => array('view'),
569 569
 					'readonly'    => true,
570 570
 				),
571 571
 				'average_total_sales' => array(
572
-					'description' => __( 'Average gross daily sales.', 'invoicing' ),
572
+					'description' => __('Average gross daily sales.', 'invoicing'),
573 573
 					'type'        => 'string',
574
-					'context'     => array( 'view' ),
574
+					'context'     => array('view'),
575 575
 					'readonly'    => true,
576 576
 				),
577 577
 				'total_invoices'      => array(
578
-					'description' => __( 'Number of paid invoices.', 'invoicing' ),
578
+					'description' => __('Number of paid invoices.', 'invoicing'),
579 579
 					'type'        => 'integer',
580
-					'context'     => array( 'view' ),
580
+					'context'     => array('view'),
581 581
 					'readonly'    => true,
582 582
 				),
583 583
 				'total_items'         => array(
584
-					'description' => __( 'Number of items purchased.', 'invoicing' ),
584
+					'description' => __('Number of items purchased.', 'invoicing'),
585 585
 					'type'        => 'integer',
586
-					'context'     => array( 'view' ),
586
+					'context'     => array('view'),
587 587
 					'readonly'    => true,
588 588
 				),
589 589
 				'refunded_items'      => array(
590
-					'description' => __( 'Number of items refunded.', 'invoicing' ),
590
+					'description' => __('Number of items refunded.', 'invoicing'),
591 591
 					'type'        => 'integer',
592
-					'context'     => array( 'view' ),
592
+					'context'     => array('view'),
593 593
 					'readonly'    => true,
594 594
 				),
595 595
 				'total_tax'           => array(
596
-					'description' => __( 'Total charged for taxes.', 'invoicing' ),
596
+					'description' => __('Total charged for taxes.', 'invoicing'),
597 597
 					'type'        => 'string',
598
-					'context'     => array( 'view' ),
598
+					'context'     => array('view'),
599 599
 					'readonly'    => true,
600 600
 				),
601 601
 				'total_refunded_tax'  => array(
602
-					'description' => __( 'Total refunded for taxes.', 'invoicing' ),
602
+					'description' => __('Total refunded for taxes.', 'invoicing'),
603 603
 					'type'        => 'string',
604
-					'context'     => array( 'view' ),
604
+					'context'     => array('view'),
605 605
 					'readonly'    => true,
606 606
 				),
607 607
 				'total_fees'          => array(
608
-					'description' => __( 'Total fees charged.', 'invoicing' ),
608
+					'description' => __('Total fees charged.', 'invoicing'),
609 609
 					'type'        => 'string',
610
-					'context'     => array( 'view' ),
610
+					'context'     => array('view'),
611 611
 					'readonly'    => true,
612 612
 				),
613 613
 				'total_refunds'       => array(
614
-					'description' => __( 'Total of refunded invoices.', 'invoicing' ),
614
+					'description' => __('Total of refunded invoices.', 'invoicing'),
615 615
 					'type'        => 'integer',
616
-					'context'     => array( 'view' ),
616
+					'context'     => array('view'),
617 617
 					'readonly'    => true,
618 618
 				),
619 619
 				'net_refunds'         => array(
620
-					'description' => __( 'Net of refunded invoices.', 'invoicing' ),
620
+					'description' => __('Net of refunded invoices.', 'invoicing'),
621 621
 					'type'        => 'integer',
622
-					'context'     => array( 'view' ),
622
+					'context'     => array('view'),
623 623
 					'readonly'    => true,
624 624
 				),
625 625
 				'total_discount'      => array(
626
-					'description' => __( 'Total of discounts used.', 'invoicing' ),
626
+					'description' => __('Total of discounts used.', 'invoicing'),
627 627
 					'type'        => 'integer',
628
-					'context'     => array( 'view' ),
628
+					'context'     => array('view'),
629 629
 					'readonly'    => true,
630 630
 				),
631 631
 				'totals'              => array(
632
-					'description' => __( 'Totals.', 'invoicing' ),
632
+					'description' => __('Totals.', 'invoicing'),
633 633
 					'type'        => 'array',
634 634
 					'items'       => array(
635 635
 						'type' => 'array',
636 636
 					),
637
-					'context'     => array( 'view' ),
637
+					'context'     => array('view'),
638 638
 					'readonly'    => true,
639 639
 				),
640 640
 				'interval'            => array(
641
-					'description' => __( 'Number of months/days in the report period.', 'invoicing' ),
641
+					'description' => __('Number of months/days in the report period.', 'invoicing'),
642 642
 					'type'        => 'integer',
643
-					'context'     => array( 'view' ),
643
+					'context'     => array('view'),
644 644
 					'readonly'    => true,
645 645
 				),
646 646
 				'previous_range'      => array(
647
-					'description' => __( 'The previous report period.', 'invoicing' ),
647
+					'description' => __('The previous report period.', 'invoicing'),
648 648
 					'type'        => 'array',
649 649
 					'items'       => array(
650 650
 						'type' => 'string',
651 651
 					),
652
-					'context'     => array( 'view' ),
652
+					'context'     => array('view'),
653 653
 					'readonly'    => true,
654 654
 				),
655 655
 				'grouped_by'          => array(
656
-					'description' => __( 'The period used to group the totals.', 'invoicing' ),
656
+					'description' => __('The period used to group the totals.', 'invoicing'),
657 657
 					'type'        => 'string',
658
-					'context'     => array( 'view' ),
659
-					'enum'        => array( 'day', 'month' ),
658
+					'context'     => array('view'),
659
+					'enum'        => array('day', 'month'),
660 660
 					'readonly'    => true,
661 661
 				),
662 662
 				'currency'            => array(
663
-					'description' => __( 'The default store currency.', 'invoicing' ),
663
+					'description' => __('The default store currency.', 'invoicing'),
664 664
 					'type'        => 'string',
665
-					'context'     => array( 'view' ),
665
+					'context'     => array('view'),
666 666
 					'readonly'    => true,
667 667
 				),
668 668
 				'currency_symbol'     => array(
669
-					'description' => __( 'The default store currency symbol.', 'invoicing' ),
669
+					'description' => __('The default store currency symbol.', 'invoicing'),
670 670
 					'type'        => 'string',
671
-					'context'     => array( 'view' ),
671
+					'context'     => array('view'),
672 672
 					'readonly'    => true,
673 673
 				),
674 674
 				'currency_position'   => array(
675
-					'description' => __( 'The default store currency position.', 'invoicing' ),
675
+					'description' => __('The default store currency position.', 'invoicing'),
676 676
 					'type'        => 'string',
677
-					'context'     => array( 'view' ),
677
+					'context'     => array('view'),
678 678
 					'readonly'    => true,
679 679
 				),
680 680
 				'decimal_places'      => array(
681
-					'description' => __( 'The default store decimal places.', 'invoicing' ),
681
+					'description' => __('The default store decimal places.', 'invoicing'),
682 682
 					'type'        => 'string',
683
-					'context'     => array( 'view' ),
683
+					'context'     => array('view'),
684 684
 					'readonly'    => true,
685 685
 				),
686 686
 				'thousands_sep'       => array(
687
-					'description' => __( 'The default store thousands separator.', 'invoicing' ),
687
+					'description' => __('The default store thousands separator.', 'invoicing'),
688 688
 					'type'        => 'string',
689
-					'context'     => array( 'view' ),
689
+					'context'     => array('view'),
690 690
 					'readonly'    => true,
691 691
 				),
692 692
 				'decimals_sep'        => array(
693
-					'description' => __( 'The default store decimals separator.', 'invoicing' ),
693
+					'description' => __('The default store decimals separator.', 'invoicing'),
694 694
 					'type'        => 'string',
695
-					'context'     => array( 'view' ),
695
+					'context'     => array('view'),
696 696
 					'readonly'    => true,
697 697
 				),
698 698
 			),
699 699
 		);
700 700
 
701
-		return $this->add_additional_fields_schema( $schema );
701
+		return $this->add_additional_fields_schema($schema);
702 702
 
703 703
 	}
704 704
 
Please login to merge, or discard this patch.
includes/api/class-getpaid-rest-date-based-controller.php 2 patches
Indentation   +492 added lines, -492 removed lines patch added patch discarded remove patch
@@ -16,496 +16,496 @@
 block discarded – undo
16 16
  */
17 17
 class GetPaid_REST_Date_Based_Controller extends GetPaid_REST_Controller {
18 18
 
19
-	/**
20
-	 * Group response items by day or month.
21
-	 *
22
-	 * @var string
23
-	 */
24
-	public $groupby = 'day';
25
-
26
-	/**
27
-	 * Returns an array with arguments to request the previous report.
28
-	 *
29
-	 * @var array
30
-	 */
31
-	public $previous_range = array();
32
-
33
-	/**
34
-	 * The period interval.
35
-	 *
36
-	 * @var int
37
-	 */
38
-	public $interval;
39
-
40
-	/**
41
-	 * Retrieves the before and after dates.
42
-	 *
43
-	 * @param WP_REST_Request $request Request object.
44
-	 * @return array The appropriate date range.
45
-	 */
46
-	public function get_date_range( $request ) {
47
-
48
-		// Check if the period is x_days.
49
-		if ( preg_match( '/^(\d+)_days$/', $request['period'], $matches ) ) {
50
-			$date_range = $this->get_x_days_date_range( absint( $matches[1] ) );
51
-		} elseif ( is_callable( array( $this, 'get_' . $request['period'] . '_date_range' ) ) ) {
52
-			$date_range = call_user_func( array( $this, 'get_' . $request['period'] . '_date_range' ), $request );
53
-		} else {
54
-			$request['period'] = '7_days';
55
-			$date_range        = $this->get_x_days_date_range();
56
-		}
57
-
58
-		// 3 months max for day view.
59
-		$before = strtotime( $date_range['before'] );
60
-		$after  = strtotime( $date_range['after'] );
61
-		if ( floor( ( $before - $after ) / MONTH_IN_SECONDS ) > 2 ) {
62
-			$this->groupby = 'month';
63
-		}
64
-
65
-		$this->prepare_interval( $date_range );
66
-
67
-		return $date_range;
68
-
69
-	}
70
-
71
-	/**
72
-	 * Groups by month or days.
73
-	 *
74
-	 * @param array $range Date range.
75
-	 * @return array The appropriate date range.
76
-	 */
77
-	public function prepare_interval( $range ) {
78
-
79
-		$before = strtotime( $range['before'] );
80
-		$after  = strtotime( $range['after'] );
81
-		if ( 'day' === $this->groupby ) {
82
-			$difference     = max( DAY_IN_SECONDS, ( DAY_IN_SECONDS + $before - $after ) ); // Prevent division by 0;
83
-			$this->interval = absint( ceil( max( 1, $difference / DAY_IN_SECONDS ) ) );
84
-			return;
85
-		}
86
-
87
-		$this->interval = 0;
88
-		$min_date       = strtotime( gmdate( 'Y-m-01', $after ) );
89
-
90
-		while ( $min_date <= $before ) {
91
-			$this->interval ++;
92
-			$min_date = strtotime( '+1 MONTH', $min_date );
93
-		}
94
-
95
-		$this->interval = max( 1, $this->interval );
96
-
97
-	}
98
-
99
-	/**
100
-	 * Retrieves a custom date range.
101
-	 *
102
-	 * @param WP_REST_Request $request Request object.
103
-	 * @return array The appropriate date range.
104
-	 */
105
-	public function get_custom_date_range( $request ) {
106
-
107
-		$after  = max( strtotime( '-20 years' ), strtotime( sanitize_text_field( $request['after'] ) ) );
108
-		$before = gmdate( 'Y-m-d' );
109
-
110
-		if ( ! empty( $request['before'] ) ) {
111
-			$before  = min( $before, strtotime( sanitize_text_field( $request['before'] ) ) );
112
-		}
113
-
114
-		// Set the previous date range.
115
-		$difference           = $before - $after;
116
-		$this->previous_range = array(
117
-			'period' => 'custom',
118
-			'before' => gmdate( 'Y-m-d', $before - $difference - DAY_IN_SECONDS ),
119
-			'after'  => gmdate( 'Y-m-d', $after - $difference - DAY_IN_SECONDS ),
120
-		);
121
-
122
-		// Generate the report.
123
-		return array(
124
-			'before' => gmdate( 'Y-m-d', $before ),
125
-			'after'  => gmdate( 'Y-m-d', $after ),
126
-		);
127
-
128
-	}
129
-
130
-	/**
131
-	 * Retrieves todays date range.
132
-	 *
133
-	 * @return array The appropriate date range.
134
-	 */
135
-	public function get_today_date_range() {
136
-
137
-		// Set the previous date range.
138
-		$this->previous_range = array(
139
-			'period' => 'yesterday',
140
-		);
141
-
142
-		// Generate the report.
143
-		return array(
144
-			'before' => gmdate( 'Y-m-d' ),
145
-			'after'  => gmdate( 'Y-m-d' ),
146
-		);
147
-
148
-	}
149
-
150
-	/**
151
-	 * Retrieves yesterdays date range.
152
-	 *
153
-	 * @return array The appropriate date range.
154
-	 */
155
-	public function get_yesterday_date_range() {
156
-
157
-		// Set the previous date range.
158
-		$this->previous_range = array(
159
-			'period' => 'custom',
160
-			'before' => gmdate( 'Y-m-d', strtotime( '-2 days' ) ),
161
-			'after'  => gmdate( 'Y-m-d', strtotime( '-2 days' ) ),
162
-		);
163
-
164
-		// Generate the report.
165
-		return array(
166
-			'before' => gmdate( 'Y-m-d', strtotime( '-1 day' ) ),
167
-			'after'  => gmdate( 'Y-m-d', strtotime( '-1 day' ) ),
168
-		);
169
-
170
-	}
171
-
172
-	/**
173
-	 * Retrieves this week's date range.
174
-	 *
175
-	 * @return array The appropriate date range.
176
-	 */
177
-	public function get_week_date_range() {
178
-
179
-		// Set the previous date range.
180
-		$this->previous_range = array(
181
-			'period' => 'last_week',
182
-		);
183
-
184
-		// Generate the report.
185
-		$week_starts = absint( get_option( 'start_of_week' ) );
186
-		return array(
187
-			'before' => gmdate( 'Y-m-d' ),
188
-			'after'  => gmdate( 'Y-m-d', strtotime( 'next Sunday -' . ( 7 - $week_starts ) . ' days' ) ),
189
-		);
190
-	}
191
-
192
-	/**
193
-	 * Retrieves last week's date range.
194
-	 *
195
-	 * @return array The appropriate date range.
196
-	 */
197
-	public function get_last_week_date_range() {
198
-
199
-		$week_starts = absint( get_option( 'start_of_week' ) );
200
-		$week_starts = strtotime( 'last Sunday -' . ( 7 - $week_starts ) . ' days' );
201
-		$date_range  = array(
202
-			'before' => gmdate( 'Y-m-d', $week_starts + 6 * DAY_IN_SECONDS ),
203
-			'after'  => gmdate( 'Y-m-d', $week_starts ),
204
-		);
205
-
206
-		// Set the previous date range.
207
-		$week_starts          = $week_starts - 7 * DAY_IN_SECONDS;
208
-		$this->previous_range = array(
209
-			'period' => 'custom',
210
-			'before' => gmdate( 'Y-m-d', $week_starts + 6 * DAY_IN_SECONDS ),
211
-			'after'  => gmdate( 'Y-m-d', $week_starts ),
212
-		);
213
-
214
-		// Generate the report.
215
-		return $date_range;
216
-	}
217
-
218
-	/**
219
-	 * Retrieves last x days date range.
220
-	 *
221
-	 * @return array The appropriate date range.
222
-	 */
223
-	public function get_x_days_date_range( $days = 7 ) {
224
-
225
-		$days--;
226
-
227
-		$date_range  = array(
228
-			'before' => gmdate( 'Y-m-d' ),
229
-			'after'  => gmdate( 'Y-m-d', strtotime( "-$days days" ) ),
230
-		);
231
-
232
-		$days++;
233
-
234
-		// Set the previous date range.
235
-		$this->previous_range = array(
236
-			'period' => 'custom',
237
-			'before' => gmdate( 'Y-m-d', strtotime( $date_range['before'] ) - $days * DAY_IN_SECONDS ),
238
-			'after'  => gmdate( 'Y-m-d', strtotime( $date_range['after'] ) - $days * DAY_IN_SECONDS ),
239
-		);
240
-
241
-		// Generate the report.
242
-		return $date_range;
243
-	}
244
-
245
-	/**
246
-	 * Retrieves this month date range.
247
-	 *
248
-	 * @return array The appropriate date range.
249
-	 */
250
-	public function get_month_date_range() {
251
-
252
-		// Set the previous date range.
253
-		$this->previous_range = array(
254
-			'period' => 'last_month',
255
-		);
256
-
257
-		// Generate the report.
258
-		return array(
259
-			'after'  => gmdate( 'Y-m-01' ),
260
-			'before' => gmdate( 'Y-m-t' ),
261
-		);
262
-
263
-	}
264
-
265
-	/**
266
-	 * Retrieves last month's date range.
267
-	 *
268
-	 * @return array The appropriate date range.
269
-	 */
270
-	public function get_last_month_date_range() {
271
-
272
-		// Set the previous date range.
273
-		$this->previous_range = array(
274
-			'period' => 'custom',
275
-			'after'  => gmdate( 'Y-m-01', strtotime( '-2 months' ) ),
276
-			'before' => gmdate( 'Y-m-t', strtotime( '-2 months' ) ),
277
-		);
278
-
279
-		// Generate the report.
280
-		return array(
281
-			'after'  => gmdate( 'Y-m-01', strtotime( 'last month' ) ),
282
-			'before' => gmdate( 'Y-m-t', strtotime( 'last month' ) ),
283
-		);
284
-
285
-	}
286
-
287
-	/**
288
-	 * Retrieves this quarter date range.
289
-	 *
290
-	 * @return array The available quarters.
291
-	 */
292
-	public function get_quarters() {
293
-
294
-		$year      = (int) gmdate( 'Y' );
295
-		$last_year = (int) $year - 1;
296
-		return array(
297
-
298
-			// Third quarter of previous year: July 1st to September 30th
299
-			array(
300
-				'before' => "{$last_year}-09-30",
301
-				'after'  => "{$last_year}-07-01",
302
-			),
303
-
304
-			// Last quarter of previous year: October 1st to December 31st
305
-			array(
306
-				'before' => "{$last_year}-12-31",
307
-        		'after'  => "{$last_year}-10-01",
308
-			),
309
-
310
-			// First quarter: January 1st to March 31st
311
-			array(
312
-				'before' => "{$year}-03-31",
313
-				'after'  => "{$year}-01-01",
314
-			),
315
-
316
-			// Second quarter: April 1st to June 30th
317
-			array(
318
-				'before' => "{$year}-06-30",
319
-				'after'  => "{$year}-04-01",
320
-			),
321
-
322
-			// Third quarter: July 1st to September 30th
323
-			array(
324
-				'before' => "{$year}-09-30",
325
-				'after'  => "{$year}-07-01",
326
-			),
327
-
328
-			// Fourth quarter: October 1st to December 31st
329
-			array(
330
-				'before' => "{$year}-12-31",
331
-				'after'  => "{$year}-10-01",
332
-			),
333
-		);
334
-	}
335
-
336
-	/**
337
-	 * Retrieves the current quater.
338
-	 *
339
-	 * @return int The current quarter.
340
-	 */
341
-	public function get_quarter() {
342
-
343
-		$month    = (int) gmdate( 'n' );
344
-		$quarters = array( 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4 );
345
-		return $quarters[ $month - 1 ];
346
-
347
-	}
348
-
349
-	/**
350
-	 * Retrieves this quarter date range.
351
-	 *
352
-	 * @return array The appropriate date range.
353
-	 */
354
-	public function get_quarter_date_range() {
355
-
356
-		// Set the previous date range.
357
-		$this->previous_range = array(
358
-			'period' => 'last_quarter',
359
-		);
360
-
361
-		// Generate the report.
362
-		$quarter  = $this->get_quarter();
363
-		$quarters = $this->get_quarters();
364
-		return $quarters[ $quarter + 1 ];
365
-
366
-	}
367
-
368
-	/**
369
-	 * Retrieves last quarter's date range.
370
-	 *
371
-	 * @return array The appropriate date range.
372
-	 */
373
-	public function get_last_quarter_date_range() {
374
-
375
-		$quarters = $this->get_quarters();
376
-		$quarter  = $this->get_quarter();
377
-
378
-		// Set the previous date range.
379
-		$this->previous_range = array_merge(
380
-			$quarters[ $quarter - 1 ],
381
-			array( 'period' => 'custom' )
382
-		);
383
-
384
-		// Generate the report.
385
-		return $quarters[ $quarter ];
386
-
387
-	}
388
-
389
-	/**
390
-	 * Retrieves this year date range.
391
-	 *
392
-	 * @return array The appropriate date range.
393
-	 */
394
-	public function get_year_date_range() {
395
-
396
-		// Set the previous date range.
397
-		$this->previous_range = array(
398
-			'period' => 'last_year',
399
-		);
400
-
401
-		// Generate the report.
402
-		return array(
403
-			'after'  => gmdate( 'Y-01-01' ),
404
-			'before' => gmdate( 'Y-12-31' ),
405
-		);
406
-
407
-	}
408
-
409
-	/**
410
-	 * Retrieves last year date range.
411
-	 *
412
-	 * @return array The appropriate date range.
413
-	 */
414
-	public function get_last_year_date_range() {
415
-
416
-		// Set the previous date range.
417
-		$this->previous_range = array(
418
-			'period' => 'custom',
419
-			'after'  => gmdate( 'Y-01-01', strtotime( '-2 years' ) ),
420
-			'before' => gmdate( 'Y-12-31', strtotime( '-2 years' ) ),
421
-		);
422
-
423
-		// Generate the report.
424
-		return array(
425
-			'after'  => gmdate( 'Y-01-01', strtotime( 'last year' ) ),
426
-			'before' => gmdate( 'Y-12-31', strtotime( 'last year' ) ),
427
-		);
428
-
429
-	}
430
-
431
-	/**
432
-	 * Prepare a the request date for SQL usage.
433
-	 *
434
-	 * @param WP_REST_Request $request Request object.
435
-	 * @param string $date_field The date field.
436
-	 * @return string The appropriate SQL.
437
-	 */
438
-	public function get_date_range_sql( $request, $date_field ) {
439
-		global $wpdb;
440
-
441
-		$sql = '1=1';
442
-		$range = $this->get_date_range( $request );
443
-
444
-		if ( ! empty( $range['after'] ) ) {
445
-			$sql .= ' AND ' . $wpdb->prepare(
446
-				"$date_field >= %s",
447
-				$range['after']
448
-			);
449
-		}
450
-
451
-		if ( ! empty( $range['before'] ) ) {
452
-			$sql .= ' AND ' . $wpdb->prepare(
453
-				"$date_field <= %s",
454
-				$range['before']
455
-			);
456
-		}
457
-
458
-		return $sql;
459
-
460
-	}
461
-
462
-	/**
463
-	 * Prepares a group by query.
464
-	 *
465
-	 * @param string $date_field The date field.
466
-	 * @return string The appropriate SQL.
467
-	 */
468
-	public function get_group_by_sql( $date_field ) {
469
-
470
-		if ( 'day' === $this->groupby ) {
471
-			return "YEAR($date_field), MONTH($date_field), DAY($date_field)";
472
-		}
473
-
474
-		return "YEAR($date_field), MONTH($date_field)";
475
-	}
476
-
477
-	/**
478
-	 * Get the query params for collections.
479
-	 *
480
-	 * @return array
481
-	 */
482
-	public function get_collection_params() {
483
-		return array(
484
-			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
485
-			'period'  => array(
486
-				'description'       => __( 'Limit to results of a specific period.', 'invoicing' ),
487
-				'type'              => 'string',
488
-				'enum'              => array( 'custom', 'today', 'yesterday', 'week', 'last_week', '7_days', '30_days', '60_days', '90_days', '180_days', 'month', 'last_month', 'quarter', 'last_quarter', 'year', 'last_year', 'quarter', 'last_quarter' ),
489
-				'validate_callback' => 'rest_validate_request_arg',
490
-				'sanitize_callback' => 'sanitize_text_field',
491
-				'default'           => '7_days',
492
-			),
493
-			'after'   => array(
494
-				/* translators: %s: date format */
495
-				'description'       => sprintf( __( 'Limit to results after a specific date, the date needs to be in the %s format.', 'invoicing' ), 'YYYY-MM-DD' ),
496
-				'type'              => 'string',
497
-				'validate_callback' => 'rest_validate_request_arg',
498
-				'sanitize_callback' => 'sanitize_text_field',
499
-				'default'           => gmdate( 'Y-m-d', strtotime( '-7 days' ) ),
500
-			),
501
-			'before'  => array(
502
-				/* translators: %s: date format */
503
-				'description'       => sprintf( __( 'Limit to results before a specific date, the date needs to be in the %s format.', 'invoicing' ), 'YYYY-MM-DD' ),
504
-				'type'              => 'string',
505
-				'validate_callback' => 'rest_validate_request_arg',
506
-				'sanitize_callback' => 'sanitize_text_field',
507
-				'default'           => gmdate( 'Y-m-d' ),
508
-			),
509
-		);
510
-	}
19
+    /**
20
+     * Group response items by day or month.
21
+     *
22
+     * @var string
23
+     */
24
+    public $groupby = 'day';
25
+
26
+    /**
27
+     * Returns an array with arguments to request the previous report.
28
+     *
29
+     * @var array
30
+     */
31
+    public $previous_range = array();
32
+
33
+    /**
34
+     * The period interval.
35
+     *
36
+     * @var int
37
+     */
38
+    public $interval;
39
+
40
+    /**
41
+     * Retrieves the before and after dates.
42
+     *
43
+     * @param WP_REST_Request $request Request object.
44
+     * @return array The appropriate date range.
45
+     */
46
+    public function get_date_range( $request ) {
47
+
48
+        // Check if the period is x_days.
49
+        if ( preg_match( '/^(\d+)_days$/', $request['period'], $matches ) ) {
50
+            $date_range = $this->get_x_days_date_range( absint( $matches[1] ) );
51
+        } elseif ( is_callable( array( $this, 'get_' . $request['period'] . '_date_range' ) ) ) {
52
+            $date_range = call_user_func( array( $this, 'get_' . $request['period'] . '_date_range' ), $request );
53
+        } else {
54
+            $request['period'] = '7_days';
55
+            $date_range        = $this->get_x_days_date_range();
56
+        }
57
+
58
+        // 3 months max for day view.
59
+        $before = strtotime( $date_range['before'] );
60
+        $after  = strtotime( $date_range['after'] );
61
+        if ( floor( ( $before - $after ) / MONTH_IN_SECONDS ) > 2 ) {
62
+            $this->groupby = 'month';
63
+        }
64
+
65
+        $this->prepare_interval( $date_range );
66
+
67
+        return $date_range;
68
+
69
+    }
70
+
71
+    /**
72
+     * Groups by month or days.
73
+     *
74
+     * @param array $range Date range.
75
+     * @return array The appropriate date range.
76
+     */
77
+    public function prepare_interval( $range ) {
78
+
79
+        $before = strtotime( $range['before'] );
80
+        $after  = strtotime( $range['after'] );
81
+        if ( 'day' === $this->groupby ) {
82
+            $difference     = max( DAY_IN_SECONDS, ( DAY_IN_SECONDS + $before - $after ) ); // Prevent division by 0;
83
+            $this->interval = absint( ceil( max( 1, $difference / DAY_IN_SECONDS ) ) );
84
+            return;
85
+        }
86
+
87
+        $this->interval = 0;
88
+        $min_date       = strtotime( gmdate( 'Y-m-01', $after ) );
89
+
90
+        while ( $min_date <= $before ) {
91
+            $this->interval ++;
92
+            $min_date = strtotime( '+1 MONTH', $min_date );
93
+        }
94
+
95
+        $this->interval = max( 1, $this->interval );
96
+
97
+    }
98
+
99
+    /**
100
+     * Retrieves a custom date range.
101
+     *
102
+     * @param WP_REST_Request $request Request object.
103
+     * @return array The appropriate date range.
104
+     */
105
+    public function get_custom_date_range( $request ) {
106
+
107
+        $after  = max( strtotime( '-20 years' ), strtotime( sanitize_text_field( $request['after'] ) ) );
108
+        $before = gmdate( 'Y-m-d' );
109
+
110
+        if ( ! empty( $request['before'] ) ) {
111
+            $before  = min( $before, strtotime( sanitize_text_field( $request['before'] ) ) );
112
+        }
113
+
114
+        // Set the previous date range.
115
+        $difference           = $before - $after;
116
+        $this->previous_range = array(
117
+            'period' => 'custom',
118
+            'before' => gmdate( 'Y-m-d', $before - $difference - DAY_IN_SECONDS ),
119
+            'after'  => gmdate( 'Y-m-d', $after - $difference - DAY_IN_SECONDS ),
120
+        );
121
+
122
+        // Generate the report.
123
+        return array(
124
+            'before' => gmdate( 'Y-m-d', $before ),
125
+            'after'  => gmdate( 'Y-m-d', $after ),
126
+        );
127
+
128
+    }
129
+
130
+    /**
131
+     * Retrieves todays date range.
132
+     *
133
+     * @return array The appropriate date range.
134
+     */
135
+    public function get_today_date_range() {
136
+
137
+        // Set the previous date range.
138
+        $this->previous_range = array(
139
+            'period' => 'yesterday',
140
+        );
141
+
142
+        // Generate the report.
143
+        return array(
144
+            'before' => gmdate( 'Y-m-d' ),
145
+            'after'  => gmdate( 'Y-m-d' ),
146
+        );
147
+
148
+    }
149
+
150
+    /**
151
+     * Retrieves yesterdays date range.
152
+     *
153
+     * @return array The appropriate date range.
154
+     */
155
+    public function get_yesterday_date_range() {
156
+
157
+        // Set the previous date range.
158
+        $this->previous_range = array(
159
+            'period' => 'custom',
160
+            'before' => gmdate( 'Y-m-d', strtotime( '-2 days' ) ),
161
+            'after'  => gmdate( 'Y-m-d', strtotime( '-2 days' ) ),
162
+        );
163
+
164
+        // Generate the report.
165
+        return array(
166
+            'before' => gmdate( 'Y-m-d', strtotime( '-1 day' ) ),
167
+            'after'  => gmdate( 'Y-m-d', strtotime( '-1 day' ) ),
168
+        );
169
+
170
+    }
171
+
172
+    /**
173
+     * Retrieves this week's date range.
174
+     *
175
+     * @return array The appropriate date range.
176
+     */
177
+    public function get_week_date_range() {
178
+
179
+        // Set the previous date range.
180
+        $this->previous_range = array(
181
+            'period' => 'last_week',
182
+        );
183
+
184
+        // Generate the report.
185
+        $week_starts = absint( get_option( 'start_of_week' ) );
186
+        return array(
187
+            'before' => gmdate( 'Y-m-d' ),
188
+            'after'  => gmdate( 'Y-m-d', strtotime( 'next Sunday -' . ( 7 - $week_starts ) . ' days' ) ),
189
+        );
190
+    }
191
+
192
+    /**
193
+     * Retrieves last week's date range.
194
+     *
195
+     * @return array The appropriate date range.
196
+     */
197
+    public function get_last_week_date_range() {
198
+
199
+        $week_starts = absint( get_option( 'start_of_week' ) );
200
+        $week_starts = strtotime( 'last Sunday -' . ( 7 - $week_starts ) . ' days' );
201
+        $date_range  = array(
202
+            'before' => gmdate( 'Y-m-d', $week_starts + 6 * DAY_IN_SECONDS ),
203
+            'after'  => gmdate( 'Y-m-d', $week_starts ),
204
+        );
205
+
206
+        // Set the previous date range.
207
+        $week_starts          = $week_starts - 7 * DAY_IN_SECONDS;
208
+        $this->previous_range = array(
209
+            'period' => 'custom',
210
+            'before' => gmdate( 'Y-m-d', $week_starts + 6 * DAY_IN_SECONDS ),
211
+            'after'  => gmdate( 'Y-m-d', $week_starts ),
212
+        );
213
+
214
+        // Generate the report.
215
+        return $date_range;
216
+    }
217
+
218
+    /**
219
+     * Retrieves last x days date range.
220
+     *
221
+     * @return array The appropriate date range.
222
+     */
223
+    public function get_x_days_date_range( $days = 7 ) {
224
+
225
+        $days--;
226
+
227
+        $date_range  = array(
228
+            'before' => gmdate( 'Y-m-d' ),
229
+            'after'  => gmdate( 'Y-m-d', strtotime( "-$days days" ) ),
230
+        );
231
+
232
+        $days++;
233
+
234
+        // Set the previous date range.
235
+        $this->previous_range = array(
236
+            'period' => 'custom',
237
+            'before' => gmdate( 'Y-m-d', strtotime( $date_range['before'] ) - $days * DAY_IN_SECONDS ),
238
+            'after'  => gmdate( 'Y-m-d', strtotime( $date_range['after'] ) - $days * DAY_IN_SECONDS ),
239
+        );
240
+
241
+        // Generate the report.
242
+        return $date_range;
243
+    }
244
+
245
+    /**
246
+     * Retrieves this month date range.
247
+     *
248
+     * @return array The appropriate date range.
249
+     */
250
+    public function get_month_date_range() {
251
+
252
+        // Set the previous date range.
253
+        $this->previous_range = array(
254
+            'period' => 'last_month',
255
+        );
256
+
257
+        // Generate the report.
258
+        return array(
259
+            'after'  => gmdate( 'Y-m-01' ),
260
+            'before' => gmdate( 'Y-m-t' ),
261
+        );
262
+
263
+    }
264
+
265
+    /**
266
+     * Retrieves last month's date range.
267
+     *
268
+     * @return array The appropriate date range.
269
+     */
270
+    public function get_last_month_date_range() {
271
+
272
+        // Set the previous date range.
273
+        $this->previous_range = array(
274
+            'period' => 'custom',
275
+            'after'  => gmdate( 'Y-m-01', strtotime( '-2 months' ) ),
276
+            'before' => gmdate( 'Y-m-t', strtotime( '-2 months' ) ),
277
+        );
278
+
279
+        // Generate the report.
280
+        return array(
281
+            'after'  => gmdate( 'Y-m-01', strtotime( 'last month' ) ),
282
+            'before' => gmdate( 'Y-m-t', strtotime( 'last month' ) ),
283
+        );
284
+
285
+    }
286
+
287
+    /**
288
+     * Retrieves this quarter date range.
289
+     *
290
+     * @return array The available quarters.
291
+     */
292
+    public function get_quarters() {
293
+
294
+        $year      = (int) gmdate( 'Y' );
295
+        $last_year = (int) $year - 1;
296
+        return array(
297
+
298
+            // Third quarter of previous year: July 1st to September 30th
299
+            array(
300
+                'before' => "{$last_year}-09-30",
301
+                'after'  => "{$last_year}-07-01",
302
+            ),
303
+
304
+            // Last quarter of previous year: October 1st to December 31st
305
+            array(
306
+                'before' => "{$last_year}-12-31",
307
+                'after'  => "{$last_year}-10-01",
308
+            ),
309
+
310
+            // First quarter: January 1st to March 31st
311
+            array(
312
+                'before' => "{$year}-03-31",
313
+                'after'  => "{$year}-01-01",
314
+            ),
315
+
316
+            // Second quarter: April 1st to June 30th
317
+            array(
318
+                'before' => "{$year}-06-30",
319
+                'after'  => "{$year}-04-01",
320
+            ),
321
+
322
+            // Third quarter: July 1st to September 30th
323
+            array(
324
+                'before' => "{$year}-09-30",
325
+                'after'  => "{$year}-07-01",
326
+            ),
327
+
328
+            // Fourth quarter: October 1st to December 31st
329
+            array(
330
+                'before' => "{$year}-12-31",
331
+                'after'  => "{$year}-10-01",
332
+            ),
333
+        );
334
+    }
335
+
336
+    /**
337
+     * Retrieves the current quater.
338
+     *
339
+     * @return int The current quarter.
340
+     */
341
+    public function get_quarter() {
342
+
343
+        $month    = (int) gmdate( 'n' );
344
+        $quarters = array( 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4 );
345
+        return $quarters[ $month - 1 ];
346
+
347
+    }
348
+
349
+    /**
350
+     * Retrieves this quarter date range.
351
+     *
352
+     * @return array The appropriate date range.
353
+     */
354
+    public function get_quarter_date_range() {
355
+
356
+        // Set the previous date range.
357
+        $this->previous_range = array(
358
+            'period' => 'last_quarter',
359
+        );
360
+
361
+        // Generate the report.
362
+        $quarter  = $this->get_quarter();
363
+        $quarters = $this->get_quarters();
364
+        return $quarters[ $quarter + 1 ];
365
+
366
+    }
367
+
368
+    /**
369
+     * Retrieves last quarter's date range.
370
+     *
371
+     * @return array The appropriate date range.
372
+     */
373
+    public function get_last_quarter_date_range() {
374
+
375
+        $quarters = $this->get_quarters();
376
+        $quarter  = $this->get_quarter();
377
+
378
+        // Set the previous date range.
379
+        $this->previous_range = array_merge(
380
+            $quarters[ $quarter - 1 ],
381
+            array( 'period' => 'custom' )
382
+        );
383
+
384
+        // Generate the report.
385
+        return $quarters[ $quarter ];
386
+
387
+    }
388
+
389
+    /**
390
+     * Retrieves this year date range.
391
+     *
392
+     * @return array The appropriate date range.
393
+     */
394
+    public function get_year_date_range() {
395
+
396
+        // Set the previous date range.
397
+        $this->previous_range = array(
398
+            'period' => 'last_year',
399
+        );
400
+
401
+        // Generate the report.
402
+        return array(
403
+            'after'  => gmdate( 'Y-01-01' ),
404
+            'before' => gmdate( 'Y-12-31' ),
405
+        );
406
+
407
+    }
408
+
409
+    /**
410
+     * Retrieves last year date range.
411
+     *
412
+     * @return array The appropriate date range.
413
+     */
414
+    public function get_last_year_date_range() {
415
+
416
+        // Set the previous date range.
417
+        $this->previous_range = array(
418
+            'period' => 'custom',
419
+            'after'  => gmdate( 'Y-01-01', strtotime( '-2 years' ) ),
420
+            'before' => gmdate( 'Y-12-31', strtotime( '-2 years' ) ),
421
+        );
422
+
423
+        // Generate the report.
424
+        return array(
425
+            'after'  => gmdate( 'Y-01-01', strtotime( 'last year' ) ),
426
+            'before' => gmdate( 'Y-12-31', strtotime( 'last year' ) ),
427
+        );
428
+
429
+    }
430
+
431
+    /**
432
+     * Prepare a the request date for SQL usage.
433
+     *
434
+     * @param WP_REST_Request $request Request object.
435
+     * @param string $date_field The date field.
436
+     * @return string The appropriate SQL.
437
+     */
438
+    public function get_date_range_sql( $request, $date_field ) {
439
+        global $wpdb;
440
+
441
+        $sql = '1=1';
442
+        $range = $this->get_date_range( $request );
443
+
444
+        if ( ! empty( $range['after'] ) ) {
445
+            $sql .= ' AND ' . $wpdb->prepare(
446
+                "$date_field >= %s",
447
+                $range['after']
448
+            );
449
+        }
450
+
451
+        if ( ! empty( $range['before'] ) ) {
452
+            $sql .= ' AND ' . $wpdb->prepare(
453
+                "$date_field <= %s",
454
+                $range['before']
455
+            );
456
+        }
457
+
458
+        return $sql;
459
+
460
+    }
461
+
462
+    /**
463
+     * Prepares a group by query.
464
+     *
465
+     * @param string $date_field The date field.
466
+     * @return string The appropriate SQL.
467
+     */
468
+    public function get_group_by_sql( $date_field ) {
469
+
470
+        if ( 'day' === $this->groupby ) {
471
+            return "YEAR($date_field), MONTH($date_field), DAY($date_field)";
472
+        }
473
+
474
+        return "YEAR($date_field), MONTH($date_field)";
475
+    }
476
+
477
+    /**
478
+     * Get the query params for collections.
479
+     *
480
+     * @return array
481
+     */
482
+    public function get_collection_params() {
483
+        return array(
484
+            'context' => $this->get_context_param( array( 'default' => 'view' ) ),
485
+            'period'  => array(
486
+                'description'       => __( 'Limit to results of a specific period.', 'invoicing' ),
487
+                'type'              => 'string',
488
+                'enum'              => array( 'custom', 'today', 'yesterday', 'week', 'last_week', '7_days', '30_days', '60_days', '90_days', '180_days', 'month', 'last_month', 'quarter', 'last_quarter', 'year', 'last_year', 'quarter', 'last_quarter' ),
489
+                'validate_callback' => 'rest_validate_request_arg',
490
+                'sanitize_callback' => 'sanitize_text_field',
491
+                'default'           => '7_days',
492
+            ),
493
+            'after'   => array(
494
+                /* translators: %s: date format */
495
+                'description'       => sprintf( __( 'Limit to results after a specific date, the date needs to be in the %s format.', 'invoicing' ), 'YYYY-MM-DD' ),
496
+                'type'              => 'string',
497
+                'validate_callback' => 'rest_validate_request_arg',
498
+                'sanitize_callback' => 'sanitize_text_field',
499
+                'default'           => gmdate( 'Y-m-d', strtotime( '-7 days' ) ),
500
+            ),
501
+            'before'  => array(
502
+                /* translators: %s: date format */
503
+                'description'       => sprintf( __( 'Limit to results before a specific date, the date needs to be in the %s format.', 'invoicing' ), 'YYYY-MM-DD' ),
504
+                'type'              => 'string',
505
+                'validate_callback' => 'rest_validate_request_arg',
506
+                'sanitize_callback' => 'sanitize_text_field',
507
+                'default'           => gmdate( 'Y-m-d' ),
508
+            ),
509
+        );
510
+    }
511 511
 }
Please login to merge, or discard this patch.
Spacing   +84 added lines, -84 removed lines patch added patch discarded remove patch
@@ -7,7 +7,7 @@  discard block
 block discarded – undo
7 7
  * @since   2.0.0
8 8
  */
9 9
 
10
-defined( 'ABSPATH' ) || exit;
10
+defined('ABSPATH') || exit;
11 11
 
12 12
 /**
13 13
  * GetPaid REST date based controller class.
@@ -43,26 +43,26 @@  discard block
 block discarded – undo
43 43
 	 * @param WP_REST_Request $request Request object.
44 44
 	 * @return array The appropriate date range.
45 45
 	 */
46
-	public function get_date_range( $request ) {
46
+	public function get_date_range($request) {
47 47
 
48 48
 		// Check if the period is x_days.
49
-		if ( preg_match( '/^(\d+)_days$/', $request['period'], $matches ) ) {
50
-			$date_range = $this->get_x_days_date_range( absint( $matches[1] ) );
51
-		} elseif ( is_callable( array( $this, 'get_' . $request['period'] . '_date_range' ) ) ) {
52
-			$date_range = call_user_func( array( $this, 'get_' . $request['period'] . '_date_range' ), $request );
49
+		if (preg_match('/^(\d+)_days$/', $request['period'], $matches)) {
50
+			$date_range = $this->get_x_days_date_range(absint($matches[1]));
51
+		} elseif (is_callable(array($this, 'get_' . $request['period'] . '_date_range'))) {
52
+			$date_range = call_user_func(array($this, 'get_' . $request['period'] . '_date_range'), $request);
53 53
 		} else {
54 54
 			$request['period'] = '7_days';
55 55
 			$date_range        = $this->get_x_days_date_range();
56 56
 		}
57 57
 
58 58
 		// 3 months max for day view.
59
-		$before = strtotime( $date_range['before'] );
60
-		$after  = strtotime( $date_range['after'] );
61
-		if ( floor( ( $before - $after ) / MONTH_IN_SECONDS ) > 2 ) {
59
+		$before = strtotime($date_range['before']);
60
+		$after  = strtotime($date_range['after']);
61
+		if (floor(($before - $after) / MONTH_IN_SECONDS) > 2) {
62 62
 			$this->groupby = 'month';
63 63
 		}
64 64
 
65
-		$this->prepare_interval( $date_range );
65
+		$this->prepare_interval($date_range);
66 66
 
67 67
 		return $date_range;
68 68
 
@@ -74,25 +74,25 @@  discard block
 block discarded – undo
74 74
 	 * @param array $range Date range.
75 75
 	 * @return array The appropriate date range.
76 76
 	 */
77
-	public function prepare_interval( $range ) {
77
+	public function prepare_interval($range) {
78 78
 
79
-		$before = strtotime( $range['before'] );
80
-		$after  = strtotime( $range['after'] );
81
-		if ( 'day' === $this->groupby ) {
82
-			$difference     = max( DAY_IN_SECONDS, ( DAY_IN_SECONDS + $before - $after ) ); // Prevent division by 0;
83
-			$this->interval = absint( ceil( max( 1, $difference / DAY_IN_SECONDS ) ) );
79
+		$before = strtotime($range['before']);
80
+		$after  = strtotime($range['after']);
81
+		if ('day' === $this->groupby) {
82
+			$difference     = max(DAY_IN_SECONDS, (DAY_IN_SECONDS + $before - $after)); // Prevent division by 0;
83
+			$this->interval = absint(ceil(max(1, $difference / DAY_IN_SECONDS)));
84 84
 			return;
85 85
 		}
86 86
 
87 87
 		$this->interval = 0;
88
-		$min_date       = strtotime( gmdate( 'Y-m-01', $after ) );
88
+		$min_date       = strtotime(gmdate('Y-m-01', $after));
89 89
 
90
-		while ( $min_date <= $before ) {
91
-			$this->interval ++;
92
-			$min_date = strtotime( '+1 MONTH', $min_date );
90
+		while ($min_date <= $before) {
91
+			$this->interval++;
92
+			$min_date = strtotime('+1 MONTH', $min_date);
93 93
 		}
94 94
 
95
-		$this->interval = max( 1, $this->interval );
95
+		$this->interval = max(1, $this->interval);
96 96
 
97 97
 	}
98 98
 
@@ -102,27 +102,27 @@  discard block
 block discarded – undo
102 102
 	 * @param WP_REST_Request $request Request object.
103 103
 	 * @return array The appropriate date range.
104 104
 	 */
105
-	public function get_custom_date_range( $request ) {
105
+	public function get_custom_date_range($request) {
106 106
 
107
-		$after  = max( strtotime( '-20 years' ), strtotime( sanitize_text_field( $request['after'] ) ) );
108
-		$before = gmdate( 'Y-m-d' );
107
+		$after  = max(strtotime('-20 years'), strtotime(sanitize_text_field($request['after'])));
108
+		$before = gmdate('Y-m-d');
109 109
 
110
-		if ( ! empty( $request['before'] ) ) {
111
-			$before  = min( $before, strtotime( sanitize_text_field( $request['before'] ) ) );
110
+		if (!empty($request['before'])) {
111
+			$before = min($before, strtotime(sanitize_text_field($request['before'])));
112 112
 		}
113 113
 
114 114
 		// Set the previous date range.
115 115
 		$difference           = $before - $after;
116 116
 		$this->previous_range = array(
117 117
 			'period' => 'custom',
118
-			'before' => gmdate( 'Y-m-d', $before - $difference - DAY_IN_SECONDS ),
119
-			'after'  => gmdate( 'Y-m-d', $after - $difference - DAY_IN_SECONDS ),
118
+			'before' => gmdate('Y-m-d', $before - $difference - DAY_IN_SECONDS),
119
+			'after'  => gmdate('Y-m-d', $after - $difference - DAY_IN_SECONDS),
120 120
 		);
121 121
 
122 122
 		// Generate the report.
123 123
 		return array(
124
-			'before' => gmdate( 'Y-m-d', $before ),
125
-			'after'  => gmdate( 'Y-m-d', $after ),
124
+			'before' => gmdate('Y-m-d', $before),
125
+			'after'  => gmdate('Y-m-d', $after),
126 126
 		);
127 127
 
128 128
 	}
@@ -141,8 +141,8 @@  discard block
 block discarded – undo
141 141
 
142 142
 		// Generate the report.
143 143
 		return array(
144
-			'before' => gmdate( 'Y-m-d' ),
145
-			'after'  => gmdate( 'Y-m-d' ),
144
+			'before' => gmdate('Y-m-d'),
145
+			'after'  => gmdate('Y-m-d'),
146 146
 		);
147 147
 
148 148
 	}
@@ -157,14 +157,14 @@  discard block
 block discarded – undo
157 157
 		// Set the previous date range.
158 158
 		$this->previous_range = array(
159 159
 			'period' => 'custom',
160
-			'before' => gmdate( 'Y-m-d', strtotime( '-2 days' ) ),
161
-			'after'  => gmdate( 'Y-m-d', strtotime( '-2 days' ) ),
160
+			'before' => gmdate('Y-m-d', strtotime('-2 days')),
161
+			'after'  => gmdate('Y-m-d', strtotime('-2 days')),
162 162
 		);
163 163
 
164 164
 		// Generate the report.
165 165
 		return array(
166
-			'before' => gmdate( 'Y-m-d', strtotime( '-1 day' ) ),
167
-			'after'  => gmdate( 'Y-m-d', strtotime( '-1 day' ) ),
166
+			'before' => gmdate('Y-m-d', strtotime('-1 day')),
167
+			'after'  => gmdate('Y-m-d', strtotime('-1 day')),
168 168
 		);
169 169
 
170 170
 	}
@@ -182,10 +182,10 @@  discard block
 block discarded – undo
182 182
 		);
183 183
 
184 184
 		// Generate the report.
185
-		$week_starts = absint( get_option( 'start_of_week' ) );
185
+		$week_starts = absint(get_option('start_of_week'));
186 186
 		return array(
187
-			'before' => gmdate( 'Y-m-d' ),
188
-			'after'  => gmdate( 'Y-m-d', strtotime( 'next Sunday -' . ( 7 - $week_starts ) . ' days' ) ),
187
+			'before' => gmdate('Y-m-d'),
188
+			'after'  => gmdate('Y-m-d', strtotime('next Sunday -' . (7 - $week_starts) . ' days')),
189 189
 		);
190 190
 	}
191 191
 
@@ -196,19 +196,19 @@  discard block
 block discarded – undo
196 196
 	 */
197 197
 	public function get_last_week_date_range() {
198 198
 
199
-		$week_starts = absint( get_option( 'start_of_week' ) );
200
-		$week_starts = strtotime( 'last Sunday -' . ( 7 - $week_starts ) . ' days' );
199
+		$week_starts = absint(get_option('start_of_week'));
200
+		$week_starts = strtotime('last Sunday -' . (7 - $week_starts) . ' days');
201 201
 		$date_range  = array(
202
-			'before' => gmdate( 'Y-m-d', $week_starts + 6 * DAY_IN_SECONDS ),
203
-			'after'  => gmdate( 'Y-m-d', $week_starts ),
202
+			'before' => gmdate('Y-m-d', $week_starts + 6 * DAY_IN_SECONDS),
203
+			'after'  => gmdate('Y-m-d', $week_starts),
204 204
 		);
205 205
 
206 206
 		// Set the previous date range.
207 207
 		$week_starts          = $week_starts - 7 * DAY_IN_SECONDS;
208 208
 		$this->previous_range = array(
209 209
 			'period' => 'custom',
210
-			'before' => gmdate( 'Y-m-d', $week_starts + 6 * DAY_IN_SECONDS ),
211
-			'after'  => gmdate( 'Y-m-d', $week_starts ),
210
+			'before' => gmdate('Y-m-d', $week_starts + 6 * DAY_IN_SECONDS),
211
+			'after'  => gmdate('Y-m-d', $week_starts),
212 212
 		);
213 213
 
214 214
 		// Generate the report.
@@ -220,13 +220,13 @@  discard block
 block discarded – undo
220 220
 	 *
221 221
 	 * @return array The appropriate date range.
222 222
 	 */
223
-	public function get_x_days_date_range( $days = 7 ) {
223
+	public function get_x_days_date_range($days = 7) {
224 224
 
225 225
 		$days--;
226 226
 
227
-		$date_range  = array(
228
-			'before' => gmdate( 'Y-m-d' ),
229
-			'after'  => gmdate( 'Y-m-d', strtotime( "-$days days" ) ),
227
+		$date_range = array(
228
+			'before' => gmdate('Y-m-d'),
229
+			'after'  => gmdate('Y-m-d', strtotime("-$days days")),
230 230
 		);
231 231
 
232 232
 		$days++;
@@ -234,8 +234,8 @@  discard block
 block discarded – undo
234 234
 		// Set the previous date range.
235 235
 		$this->previous_range = array(
236 236
 			'period' => 'custom',
237
-			'before' => gmdate( 'Y-m-d', strtotime( $date_range['before'] ) - $days * DAY_IN_SECONDS ),
238
-			'after'  => gmdate( 'Y-m-d', strtotime( $date_range['after'] ) - $days * DAY_IN_SECONDS ),
237
+			'before' => gmdate('Y-m-d', strtotime($date_range['before']) - $days * DAY_IN_SECONDS),
238
+			'after'  => gmdate('Y-m-d', strtotime($date_range['after']) - $days * DAY_IN_SECONDS),
239 239
 		);
240 240
 
241 241
 		// Generate the report.
@@ -256,8 +256,8 @@  discard block
 block discarded – undo
256 256
 
257 257
 		// Generate the report.
258 258
 		return array(
259
-			'after'  => gmdate( 'Y-m-01' ),
260
-			'before' => gmdate( 'Y-m-t' ),
259
+			'after'  => gmdate('Y-m-01'),
260
+			'before' => gmdate('Y-m-t'),
261 261
 		);
262 262
 
263 263
 	}
@@ -272,14 +272,14 @@  discard block
 block discarded – undo
272 272
 		// Set the previous date range.
273 273
 		$this->previous_range = array(
274 274
 			'period' => 'custom',
275
-			'after'  => gmdate( 'Y-m-01', strtotime( '-2 months' ) ),
276
-			'before' => gmdate( 'Y-m-t', strtotime( '-2 months' ) ),
275
+			'after'  => gmdate('Y-m-01', strtotime('-2 months')),
276
+			'before' => gmdate('Y-m-t', strtotime('-2 months')),
277 277
 		);
278 278
 
279 279
 		// Generate the report.
280 280
 		return array(
281
-			'after'  => gmdate( 'Y-m-01', strtotime( 'last month' ) ),
282
-			'before' => gmdate( 'Y-m-t', strtotime( 'last month' ) ),
281
+			'after'  => gmdate('Y-m-01', strtotime('last month')),
282
+			'before' => gmdate('Y-m-t', strtotime('last month')),
283 283
 		);
284 284
 
285 285
 	}
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
 	 */
292 292
 	public function get_quarters() {
293 293
 
294
-		$year      = (int) gmdate( 'Y' );
294
+		$year      = (int) gmdate('Y');
295 295
 		$last_year = (int) $year - 1;
296 296
 		return array(
297 297
 
@@ -340,9 +340,9 @@  discard block
 block discarded – undo
340 340
 	 */
341 341
 	public function get_quarter() {
342 342
 
343
-		$month    = (int) gmdate( 'n' );
344
-		$quarters = array( 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4 );
345
-		return $quarters[ $month - 1 ];
343
+		$month    = (int) gmdate('n');
344
+		$quarters = array(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4);
345
+		return $quarters[$month - 1];
346 346
 
347 347
 	}
348 348
 
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
 		// Generate the report.
362 362
 		$quarter  = $this->get_quarter();
363 363
 		$quarters = $this->get_quarters();
364
-		return $quarters[ $quarter + 1 ];
364
+		return $quarters[$quarter + 1];
365 365
 
366 366
 	}
367 367
 
@@ -377,12 +377,12 @@  discard block
 block discarded – undo
377 377
 
378 378
 		// Set the previous date range.
379 379
 		$this->previous_range = array_merge(
380
-			$quarters[ $quarter - 1 ],
381
-			array( 'period' => 'custom' )
380
+			$quarters[$quarter - 1],
381
+			array('period' => 'custom')
382 382
 		);
383 383
 
384 384
 		// Generate the report.
385
-		return $quarters[ $quarter ];
385
+		return $quarters[$quarter];
386 386
 
387 387
 	}
388 388
 
@@ -400,8 +400,8 @@  discard block
 block discarded – undo
400 400
 
401 401
 		// Generate the report.
402 402
 		return array(
403
-			'after'  => gmdate( 'Y-01-01' ),
404
-			'before' => gmdate( 'Y-12-31' ),
403
+			'after'  => gmdate('Y-01-01'),
404
+			'before' => gmdate('Y-12-31'),
405 405
 		);
406 406
 
407 407
 	}
@@ -416,14 +416,14 @@  discard block
 block discarded – undo
416 416
 		// Set the previous date range.
417 417
 		$this->previous_range = array(
418 418
 			'period' => 'custom',
419
-			'after'  => gmdate( 'Y-01-01', strtotime( '-2 years' ) ),
420
-			'before' => gmdate( 'Y-12-31', strtotime( '-2 years' ) ),
419
+			'after'  => gmdate('Y-01-01', strtotime('-2 years')),
420
+			'before' => gmdate('Y-12-31', strtotime('-2 years')),
421 421
 		);
422 422
 
423 423
 		// Generate the report.
424 424
 		return array(
425
-			'after'  => gmdate( 'Y-01-01', strtotime( 'last year' ) ),
426
-			'before' => gmdate( 'Y-12-31', strtotime( 'last year' ) ),
425
+			'after'  => gmdate('Y-01-01', strtotime('last year')),
426
+			'before' => gmdate('Y-12-31', strtotime('last year')),
427 427
 		);
428 428
 
429 429
 	}
@@ -435,20 +435,20 @@  discard block
 block discarded – undo
435 435
 	 * @param string $date_field The date field.
436 436
 	 * @return string The appropriate SQL.
437 437
 	 */
438
-	public function get_date_range_sql( $request, $date_field ) {
438
+	public function get_date_range_sql($request, $date_field) {
439 439
 		global $wpdb;
440 440
 
441 441
 		$sql = '1=1';
442
-		$range = $this->get_date_range( $request );
442
+		$range = $this->get_date_range($request);
443 443
 
444
-		if ( ! empty( $range['after'] ) ) {
444
+		if (!empty($range['after'])) {
445 445
 			$sql .= ' AND ' . $wpdb->prepare(
446 446
 				"$date_field >= %s",
447 447
 				$range['after']
448 448
 			);
449 449
 		}
450 450
 
451
-		if ( ! empty( $range['before'] ) ) {
451
+		if (!empty($range['before'])) {
452 452
 			$sql .= ' AND ' . $wpdb->prepare(
453 453
 				"$date_field <= %s",
454 454
 				$range['before']
@@ -465,9 +465,9 @@  discard block
 block discarded – undo
465 465
 	 * @param string $date_field The date field.
466 466
 	 * @return string The appropriate SQL.
467 467
 	 */
468
-	public function get_group_by_sql( $date_field ) {
468
+	public function get_group_by_sql($date_field) {
469 469
 
470
-		if ( 'day' === $this->groupby ) {
470
+		if ('day' === $this->groupby) {
471 471
 			return "YEAR($date_field), MONTH($date_field), DAY($date_field)";
472 472
 		}
473 473
 
@@ -481,30 +481,30 @@  discard block
 block discarded – undo
481 481
 	 */
482 482
 	public function get_collection_params() {
483 483
 		return array(
484
-			'context' => $this->get_context_param( array( 'default' => 'view' ) ),
484
+			'context' => $this->get_context_param(array('default' => 'view')),
485 485
 			'period'  => array(
486
-				'description'       => __( 'Limit to results of a specific period.', 'invoicing' ),
486
+				'description'       => __('Limit to results of a specific period.', 'invoicing'),
487 487
 				'type'              => 'string',
488
-				'enum'              => array( 'custom', 'today', 'yesterday', 'week', 'last_week', '7_days', '30_days', '60_days', '90_days', '180_days', 'month', 'last_month', 'quarter', 'last_quarter', 'year', 'last_year', 'quarter', 'last_quarter' ),
488
+				'enum'              => array('custom', 'today', 'yesterday', 'week', 'last_week', '7_days', '30_days', '60_days', '90_days', '180_days', 'month', 'last_month', 'quarter', 'last_quarter', 'year', 'last_year', 'quarter', 'last_quarter'),
489 489
 				'validate_callback' => 'rest_validate_request_arg',
490 490
 				'sanitize_callback' => 'sanitize_text_field',
491 491
 				'default'           => '7_days',
492 492
 			),
493 493
 			'after'   => array(
494 494
 				/* translators: %s: date format */
495
-				'description'       => sprintf( __( 'Limit to results after a specific date, the date needs to be in the %s format.', 'invoicing' ), 'YYYY-MM-DD' ),
495
+				'description'       => sprintf(__('Limit to results after a specific date, the date needs to be in the %s format.', 'invoicing'), 'YYYY-MM-DD'),
496 496
 				'type'              => 'string',
497 497
 				'validate_callback' => 'rest_validate_request_arg',
498 498
 				'sanitize_callback' => 'sanitize_text_field',
499
-				'default'           => gmdate( 'Y-m-d', strtotime( '-7 days' ) ),
499
+				'default'           => gmdate('Y-m-d', strtotime('-7 days')),
500 500
 			),
501 501
 			'before'  => array(
502 502
 				/* translators: %s: date format */
503
-				'description'       => sprintf( __( 'Limit to results before a specific date, the date needs to be in the %s format.', 'invoicing' ), 'YYYY-MM-DD' ),
503
+				'description'       => sprintf(__('Limit to results before a specific date, the date needs to be in the %s format.', 'invoicing'), 'YYYY-MM-DD'),
504 504
 				'type'              => 'string',
505 505
 				'validate_callback' => 'rest_validate_request_arg',
506 506
 				'sanitize_callback' => 'sanitize_text_field',
507
-				'default'           => gmdate( 'Y-m-d' ),
507
+				'default'           => gmdate('Y-m-d'),
508 508
 			),
509 509
 		);
510 510
 	}
Please login to merge, or discard this patch.
includes/reports/class-getpaid-reports-helper.php 2 patches
Indentation   +276 added lines, -276 removed lines patch added patch discarded remove patch
@@ -12,294 +12,294 @@
 block discarded – undo
12 12
  */
13 13
 class GetPaid_Reports_Helper {
14 14
 
15
-	/**
16
-	 * Get report totals such as invoice totals and discount amounts.
17
-	 *
18
-	 * Data example:
19
-	 *
20
-	 * 'subtotal' => array(
21
-	 *     'type'     => 'invoice_data',
22
-	 *     'function' => 'SUM',
23
-	 *     'name'     => 'subtotal'
24
-	 * )
25
-	 *
26
-	 * @param  array $args
27
-	 * @return mixed depending on query_type
28
-	 */
29
-	public static function get_invoice_report_data( $args = array() ) {
30
-		global $wpdb;
31
-
32
-		$default_args = array(
33
-			'data'                  => array(), // The data to retrieve.
34
-			'where'                 => array(), // An array of where queries.
35
-			'query_type'            => 'get_row', // wpdb query to run.
36
-			'group_by'              => '', // What to group results by.
37
-			'order_by'              => '', // What to order by.
38
-			'limit'                 => '', // Results limit.
39
-			'filter_range'          => array(), // An array of before and after dates to limit results by.
40
-			'invoice_types'         => array( 'wpi_invoice' ), // An array of post types to retrieve.
41
-			'invoice_status'        => array( 'publish', 'wpi-processing', 'wpi-onhold' ),
42
-			'parent_invoice_status' => false, // Optionally filter by parent invoice status.
43
-		);
44
-
45
-		$args         = apply_filters( 'getpaid_reports_get_invoice_report_data_args', $args );
46
-		$args         = wp_parse_args( $args, $default_args );
47
-
48
-		extract( $args );
49
-
50
-		if ( empty( $data ) ) {
51
-			return '';
52
-		}
53
-
54
-		$query           = array();
55
-		$query['select'] = 'SELECT ' . implode( ',', self::prepare_invoice_data( $data ) );
56
-		$query['from']   = "FROM {$wpdb->posts} AS posts";
57
-		$query['join']   = implode( ' ', self::prepare_invoice_joins( $data + $where, ! empty( $parent_invoice_status ) ) );
58
-
59
-		$query['where']  = "
15
+    /**
16
+     * Get report totals such as invoice totals and discount amounts.
17
+     *
18
+     * Data example:
19
+     *
20
+     * 'subtotal' => array(
21
+     *     'type'     => 'invoice_data',
22
+     *     'function' => 'SUM',
23
+     *     'name'     => 'subtotal'
24
+     * )
25
+     *
26
+     * @param  array $args
27
+     * @return mixed depending on query_type
28
+     */
29
+    public static function get_invoice_report_data( $args = array() ) {
30
+        global $wpdb;
31
+
32
+        $default_args = array(
33
+            'data'                  => array(), // The data to retrieve.
34
+            'where'                 => array(), // An array of where queries.
35
+            'query_type'            => 'get_row', // wpdb query to run.
36
+            'group_by'              => '', // What to group results by.
37
+            'order_by'              => '', // What to order by.
38
+            'limit'                 => '', // Results limit.
39
+            'filter_range'          => array(), // An array of before and after dates to limit results by.
40
+            'invoice_types'         => array( 'wpi_invoice' ), // An array of post types to retrieve.
41
+            'invoice_status'        => array( 'publish', 'wpi-processing', 'wpi-onhold' ),
42
+            'parent_invoice_status' => false, // Optionally filter by parent invoice status.
43
+        );
44
+
45
+        $args         = apply_filters( 'getpaid_reports_get_invoice_report_data_args', $args );
46
+        $args         = wp_parse_args( $args, $default_args );
47
+
48
+        extract( $args );
49
+
50
+        if ( empty( $data ) ) {
51
+            return '';
52
+        }
53
+
54
+        $query           = array();
55
+        $query['select'] = 'SELECT ' . implode( ',', self::prepare_invoice_data( $data ) );
56
+        $query['from']   = "FROM {$wpdb->posts} AS posts";
57
+        $query['join']   = implode( ' ', self::prepare_invoice_joins( $data + $where, ! empty( $parent_invoice_status ) ) );
58
+
59
+        $query['where']  = "
60 60
 			WHERE 	posts.post_type 	IN ( '" . implode( "','", $invoice_types ) . "' )
61 61
 			";
62 62
 
63
-		if ( ! empty( $invoice_status ) ) {
64
-			$query['where'] .= "
63
+        if ( ! empty( $invoice_status ) ) {
64
+            $query['where'] .= "
65 65
 				AND 	posts.post_status 	IN ( '" . implode( "','", $invoice_status ) . "' )
66 66
 			";
67
-		}
68
-
69
-		if ( ! empty( $parent_invoice_status ) ) {
70
-			if ( ! empty( $invoice_status ) ) {
71
-				$query['where'] .= " AND ( parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) OR parent.ID IS NULL ) ";
72
-			} else {
73
-				$query['where'] .= " AND parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) ";
74
-			}
75
-		}
76
-
77
-		if ( ! empty( $filter_range['before'] ) ) {
78
-			$query['where'] .= "
67
+        }
68
+
69
+        if ( ! empty( $parent_invoice_status ) ) {
70
+            if ( ! empty( $invoice_status ) ) {
71
+                $query['where'] .= " AND ( parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) OR parent.ID IS NULL ) ";
72
+            } else {
73
+                $query['where'] .= " AND parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) ";
74
+            }
75
+        }
76
+
77
+        if ( ! empty( $filter_range['before'] ) ) {
78
+            $query['where'] .= "
79 79
 				AND 	posts.post_date <= '" . gmdate( 'Y-m-d 23:59:59', strtotime( $filter_range['before'] ) ) . "'
80 80
 			";
81
-		}
81
+        }
82 82
 
83
-		if ( ! empty( $filter_range['after'] ) ) {
84
-			$query['where'] .= "
83
+        if ( ! empty( $filter_range['after'] ) ) {
84
+            $query['where'] .= "
85 85
 				AND 	posts.post_date >= '" . gmdate( 'Y-m-d 00:00:00', strtotime( $filter_range['after'] ) ) . "'
86 86
 			";
87
-		}
87
+        }
88 88
 
89
-		if ( ! empty( $where ) ) {
89
+        if ( ! empty( $where ) ) {
90 90
 
91
-			foreach ( $where as $value ) {
91
+            foreach ( $where as $value ) {
92 92
 
93
-				if ( strtolower( $value['operator'] ) === 'in' || strtolower( $value['operator'] ) === 'not in' ) {
94
-
95
-					if ( is_array( $value['value'] ) ) {
96
-						$value['value'] = implode( "','", $value['value'] );
97
-					}
98
-
99
-					if ( ! empty( $value['value'] ) ) {
100
-						$where_value = "{$value['operator']} ('{$value['value']}')";
101
-					}
102
-				} else {
103
-					$where_value = "{$value['operator']} '{$value['value']}'";
104
-				}
105
-
106
-				if ( ! empty( $where_value ) ) {
107
-					$query['where'] .= " AND {$value['key']} {$where_value}";
108
-				}
109
-			}
110
-		}
111
-
112
-		if ( $group_by ) {
113
-			$query['group_by'] = "GROUP BY {$group_by}";
114
-		}
115
-
116
-		if ( $order_by ) {
117
-			$query['order_by'] = "ORDER BY {$order_by}";
118
-		}
119
-
120
-		if ( $limit ) {
121
-			$query['limit'] = "LIMIT {$limit}";
122
-		}
123
-
124
-		$query = apply_filters( 'getpaid_reports_get_invoice_report_query', $query, $data );
125
-		$query = implode( ' ', $query );
126
-
127
-		return self::execute( $query_type, $query );
128
-
129
-	}
130
-
131
-	/**
132
-	 * Prepares the data to select.
133
-	 *
134
-	 *
135
-	 * @param  array $data
136
-	 * @return array
137
-	 */
138
-	public static function prepare_invoice_data( $data ) {
139
-
140
-		$prepared = array();
141
-
142
-		foreach ( $data as $raw_key => $value ) {
143
-			$key      = sanitize_key( $raw_key );
144
-			$distinct = '';
145
-
146
-			if ( isset( $value['distinct'] ) ) {
147
-				$distinct = 'DISTINCT';
148
-			}
149
-
150
-			$get_key = self::get_invoice_table_key( $key, $value['type'] );
151
-
152
-			if ( false === $get_key ) {
153
-				// Skip to the next foreach iteration else the query will be invalid.
154
-				continue;
155
-			}
156
-
157
-			if ( ! empty( $value['function'] ) ) {
158
-				$get = "{$value['function']}({$distinct} {$get_key})";
159
-			} else {
160
-				$get = "{$distinct} {$get_key}";
161
-			}
162
-
163
-			$prepared[] = "{$get} as {$value['name']}";
164
-		}
165
-
166
-		return $prepared;
167
-
168
-	}
169
-
170
-	/**
171
-	 * Prepares the joins to use.
172
-	 *
173
-	 *
174
-	 * @param  array $data
175
-	 * @param  bool $with_parent
176
-	 * @return array
177
-	 */
178
-	public static function prepare_invoice_joins( $data, $with_parent ) {
179
-		global $wpdb;
180
-
181
-		$prepared = array();
182
-
183
-		foreach ( $data as $raw_key => $value ) {
184
-			$join_type = isset( $value['join_type'] ) ? $value['join_type'] : 'INNER';
185
-			$type      = isset( $value['type'] ) ? $value['type'] : false;
186
-			$key       = sanitize_key( $raw_key );
187
-
188
-			switch ( $type ) {
189
-				case 'meta':
190
-					$prepared[ "meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS meta_{$key} ON ( posts.ID = meta_{$key}.post_id AND meta_{$key}.meta_key = '{$raw_key}' )";
191
-					break;
192
-				case 'parent_meta':
193
-					$prepared[ "parent_meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS parent_meta_{$key} ON (posts.post_parent = parent_meta_{$key}.post_id) AND (parent_meta_{$key}.meta_key = '{$raw_key}')";
194
-					break;
195
-				case 'invoice_data':
196
-					$prepared['invoices'] = "{$join_type} JOIN {$wpdb->prefix}getpaid_invoices AS invoices ON posts.ID = invoices.post_id";
197
-					break;
198
-				case 'invoice_item':
199
-					$prepared['invoice_items'] = "{$join_type} JOIN {$wpdb->prefix}getpaid_invoice_items AS invoice_items ON posts.ID = invoice_items.post_id";
200
-					break;
201
-			}
202
-		}
203
-
204
-		if ( $with_parent ) {
205
-			$prepared['parent'] = "LEFT JOIN {$wpdb->posts} AS parent ON posts.post_parent = parent.ID";
206
-		}
207
-
208
-		return $prepared;
209
-
210
-	}
211
-
212
-	/**
213
-	 * Retrieves the appropriate table key to use.
214
-	 *
215
-	 *
216
-	 * @param  string $key
217
-	 * @param  string $table
218
-	 * @return string|false
219
-	 */
220
-	public static function get_invoice_table_key( $key, $table ) {
221
-
222
-		$keys = array(
223
-			'meta'         => "meta_{$key}.meta_value",
224
-			'parent_meta'  => "parent_meta_{$key}.meta_value",
225
-			'post_data'    => "posts.{$key}",
226
-			'invoice_data' => "invoices.{$key}",
227
-			'invoice_item' => "invoice_items.{$key}",
228
-		);
229
-
230
-		return isset( $keys[ $table ] ) ? $keys[ $table ] : false;
231
-
232
-	}
233
-
234
-	/**
235
-	 * Executes a query and caches the result for a minute.
236
-	 *
237
-	 *
238
-	 * @param  string $query_type
239
-	 * @param  string $query
240
-	 * @return mixed depending on query_type
241
-	 */
242
-	public static function execute( $query_type, $query ) {
243
-		global $wpdb;
244
-
245
-		$query_hash = md5( $query_type . $query );
246
-		$result     = self::get_cached_query( $query_hash );
247
-		if ( $result === false ) {
248
-			self::enable_big_selects();
249
-
250
-			$result = $wpdb->$query_type( $query );
251
-			self::set_cached_query( $query_hash, $result );
252
-		}
253
-
254
-		return $result;
255
-
256
-	}
257
-
258
-	/**
259
-	 * Enables big mysql selects for reports, just once for this session.
260
-	 */
261
-	protected static function enable_big_selects() {
262
-		static $big_selects = false;
263
-
264
-		global $wpdb;
265
-
266
-		if ( ! $big_selects ) {
267
-			$wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' );
268
-			$big_selects = true;
269
-		}
270
-	}
271
-
272
-	/**
273
-	 * Get the cached query result or null if it's not in the cache.
274
-	 *
275
-	 * @param string $query_hash The query hash.
276
-	 *
277
-	 * @return mixed|false The cache contents on success, false on failure to retrieve contents.
278
-	 */
279
-	protected static function get_cached_query( $query_hash ) {
280
-
281
-		return wp_cache_get(
282
-			$query_hash,
283
-			strtolower( __CLASS__ )
284
-		);
285
-
286
-	}
287
-
288
-	/**
289
-	 * Set the cached query result.
290
-	 *
291
-	 * @param string $query_hash The query hash.
292
-	 * @param mixed  $data The data to cache.
293
-	 */
294
-	protected static function set_cached_query( $query_hash, $data ) {
295
-
296
-		wp_cache_set(
297
-			$query_hash,
298
-			$data,
299
-			strtolower( __CLASS__ ),
300
-			MINUTE_IN_SECONDS
301
-		);
302
-
303
-	}
93
+                if ( strtolower( $value['operator'] ) === 'in' || strtolower( $value['operator'] ) === 'not in' ) {
94
+
95
+                    if ( is_array( $value['value'] ) ) {
96
+                        $value['value'] = implode( "','", $value['value'] );
97
+                    }
98
+
99
+                    if ( ! empty( $value['value'] ) ) {
100
+                        $where_value = "{$value['operator']} ('{$value['value']}')";
101
+                    }
102
+                } else {
103
+                    $where_value = "{$value['operator']} '{$value['value']}'";
104
+                }
105
+
106
+                if ( ! empty( $where_value ) ) {
107
+                    $query['where'] .= " AND {$value['key']} {$where_value}";
108
+                }
109
+            }
110
+        }
111
+
112
+        if ( $group_by ) {
113
+            $query['group_by'] = "GROUP BY {$group_by}";
114
+        }
115
+
116
+        if ( $order_by ) {
117
+            $query['order_by'] = "ORDER BY {$order_by}";
118
+        }
119
+
120
+        if ( $limit ) {
121
+            $query['limit'] = "LIMIT {$limit}";
122
+        }
123
+
124
+        $query = apply_filters( 'getpaid_reports_get_invoice_report_query', $query, $data );
125
+        $query = implode( ' ', $query );
126
+
127
+        return self::execute( $query_type, $query );
128
+
129
+    }
130
+
131
+    /**
132
+     * Prepares the data to select.
133
+     *
134
+     *
135
+     * @param  array $data
136
+     * @return array
137
+     */
138
+    public static function prepare_invoice_data( $data ) {
139
+
140
+        $prepared = array();
141
+
142
+        foreach ( $data as $raw_key => $value ) {
143
+            $key      = sanitize_key( $raw_key );
144
+            $distinct = '';
145
+
146
+            if ( isset( $value['distinct'] ) ) {
147
+                $distinct = 'DISTINCT';
148
+            }
149
+
150
+            $get_key = self::get_invoice_table_key( $key, $value['type'] );
151
+
152
+            if ( false === $get_key ) {
153
+                // Skip to the next foreach iteration else the query will be invalid.
154
+                continue;
155
+            }
156
+
157
+            if ( ! empty( $value['function'] ) ) {
158
+                $get = "{$value['function']}({$distinct} {$get_key})";
159
+            } else {
160
+                $get = "{$distinct} {$get_key}";
161
+            }
162
+
163
+            $prepared[] = "{$get} as {$value['name']}";
164
+        }
165
+
166
+        return $prepared;
167
+
168
+    }
169
+
170
+    /**
171
+     * Prepares the joins to use.
172
+     *
173
+     *
174
+     * @param  array $data
175
+     * @param  bool $with_parent
176
+     * @return array
177
+     */
178
+    public static function prepare_invoice_joins( $data, $with_parent ) {
179
+        global $wpdb;
180
+
181
+        $prepared = array();
182
+
183
+        foreach ( $data as $raw_key => $value ) {
184
+            $join_type = isset( $value['join_type'] ) ? $value['join_type'] : 'INNER';
185
+            $type      = isset( $value['type'] ) ? $value['type'] : false;
186
+            $key       = sanitize_key( $raw_key );
187
+
188
+            switch ( $type ) {
189
+                case 'meta':
190
+                    $prepared[ "meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS meta_{$key} ON ( posts.ID = meta_{$key}.post_id AND meta_{$key}.meta_key = '{$raw_key}' )";
191
+                    break;
192
+                case 'parent_meta':
193
+                    $prepared[ "parent_meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS parent_meta_{$key} ON (posts.post_parent = parent_meta_{$key}.post_id) AND (parent_meta_{$key}.meta_key = '{$raw_key}')";
194
+                    break;
195
+                case 'invoice_data':
196
+                    $prepared['invoices'] = "{$join_type} JOIN {$wpdb->prefix}getpaid_invoices AS invoices ON posts.ID = invoices.post_id";
197
+                    break;
198
+                case 'invoice_item':
199
+                    $prepared['invoice_items'] = "{$join_type} JOIN {$wpdb->prefix}getpaid_invoice_items AS invoice_items ON posts.ID = invoice_items.post_id";
200
+                    break;
201
+            }
202
+        }
203
+
204
+        if ( $with_parent ) {
205
+            $prepared['parent'] = "LEFT JOIN {$wpdb->posts} AS parent ON posts.post_parent = parent.ID";
206
+        }
207
+
208
+        return $prepared;
209
+
210
+    }
211
+
212
+    /**
213
+     * Retrieves the appropriate table key to use.
214
+     *
215
+     *
216
+     * @param  string $key
217
+     * @param  string $table
218
+     * @return string|false
219
+     */
220
+    public static function get_invoice_table_key( $key, $table ) {
221
+
222
+        $keys = array(
223
+            'meta'         => "meta_{$key}.meta_value",
224
+            'parent_meta'  => "parent_meta_{$key}.meta_value",
225
+            'post_data'    => "posts.{$key}",
226
+            'invoice_data' => "invoices.{$key}",
227
+            'invoice_item' => "invoice_items.{$key}",
228
+        );
229
+
230
+        return isset( $keys[ $table ] ) ? $keys[ $table ] : false;
231
+
232
+    }
233
+
234
+    /**
235
+     * Executes a query and caches the result for a minute.
236
+     *
237
+     *
238
+     * @param  string $query_type
239
+     * @param  string $query
240
+     * @return mixed depending on query_type
241
+     */
242
+    public static function execute( $query_type, $query ) {
243
+        global $wpdb;
244
+
245
+        $query_hash = md5( $query_type . $query );
246
+        $result     = self::get_cached_query( $query_hash );
247
+        if ( $result === false ) {
248
+            self::enable_big_selects();
249
+
250
+            $result = $wpdb->$query_type( $query );
251
+            self::set_cached_query( $query_hash, $result );
252
+        }
253
+
254
+        return $result;
255
+
256
+    }
257
+
258
+    /**
259
+     * Enables big mysql selects for reports, just once for this session.
260
+     */
261
+    protected static function enable_big_selects() {
262
+        static $big_selects = false;
263
+
264
+        global $wpdb;
265
+
266
+        if ( ! $big_selects ) {
267
+            $wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' );
268
+            $big_selects = true;
269
+        }
270
+    }
271
+
272
+    /**
273
+     * Get the cached query result or null if it's not in the cache.
274
+     *
275
+     * @param string $query_hash The query hash.
276
+     *
277
+     * @return mixed|false The cache contents on success, false on failure to retrieve contents.
278
+     */
279
+    protected static function get_cached_query( $query_hash ) {
280
+
281
+        return wp_cache_get(
282
+            $query_hash,
283
+            strtolower( __CLASS__ )
284
+        );
285
+
286
+    }
287
+
288
+    /**
289
+     * Set the cached query result.
290
+     *
291
+     * @param string $query_hash The query hash.
292
+     * @param mixed  $data The data to cache.
293
+     */
294
+    protected static function set_cached_query( $query_hash, $data ) {
295
+
296
+        wp_cache_set(
297
+            $query_hash,
298
+            $data,
299
+            strtolower( __CLASS__ ),
300
+            MINUTE_IN_SECONDS
301
+        );
302
+
303
+    }
304 304
 
305 305
 }
Please login to merge, or discard this patch.
Spacing   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -5,7 +5,7 @@  discard block
 block discarded – undo
5 5
  *
6 6
  */
7 7
 
8
-defined( 'ABSPATH' ) || exit;
8
+defined('ABSPATH') || exit;
9 9
 
10 10
 /**
11 11
  * GetPaid_Reports_Helper Class.
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
 	 * @param  array $args
27 27
 	 * @return mixed depending on query_type
28 28
 	 */
29
-	public static function get_invoice_report_data( $args = array() ) {
29
+	public static function get_invoice_report_data($args = array()) {
30 30
 		global $wpdb;
31 31
 
32 32
 		$default_args = array(
@@ -37,94 +37,94 @@  discard block
 block discarded – undo
37 37
 			'order_by'              => '', // What to order by.
38 38
 			'limit'                 => '', // Results limit.
39 39
 			'filter_range'          => array(), // An array of before and after dates to limit results by.
40
-			'invoice_types'         => array( 'wpi_invoice' ), // An array of post types to retrieve.
41
-			'invoice_status'        => array( 'publish', 'wpi-processing', 'wpi-onhold' ),
40
+			'invoice_types'         => array('wpi_invoice'), // An array of post types to retrieve.
41
+			'invoice_status'        => array('publish', 'wpi-processing', 'wpi-onhold'),
42 42
 			'parent_invoice_status' => false, // Optionally filter by parent invoice status.
43 43
 		);
44 44
 
45
-		$args         = apply_filters( 'getpaid_reports_get_invoice_report_data_args', $args );
46
-		$args         = wp_parse_args( $args, $default_args );
45
+		$args         = apply_filters('getpaid_reports_get_invoice_report_data_args', $args);
46
+		$args         = wp_parse_args($args, $default_args);
47 47
 
48
-		extract( $args );
48
+		extract($args);
49 49
 
50
-		if ( empty( $data ) ) {
50
+		if (empty($data)) {
51 51
 			return '';
52 52
 		}
53 53
 
54 54
 		$query           = array();
55
-		$query['select'] = 'SELECT ' . implode( ',', self::prepare_invoice_data( $data ) );
55
+		$query['select'] = 'SELECT ' . implode(',', self::prepare_invoice_data($data));
56 56
 		$query['from']   = "FROM {$wpdb->posts} AS posts";
57
-		$query['join']   = implode( ' ', self::prepare_invoice_joins( $data + $where, ! empty( $parent_invoice_status ) ) );
57
+		$query['join']   = implode(' ', self::prepare_invoice_joins($data + $where, !empty($parent_invoice_status)));
58 58
 
59 59
 		$query['where']  = "
60
-			WHERE 	posts.post_type 	IN ( '" . implode( "','", $invoice_types ) . "' )
60
+			WHERE 	posts.post_type 	IN ( '" . implode("','", $invoice_types) . "' )
61 61
 			";
62 62
 
63
-		if ( ! empty( $invoice_status ) ) {
63
+		if (!empty($invoice_status)) {
64 64
 			$query['where'] .= "
65
-				AND 	posts.post_status 	IN ( '" . implode( "','", $invoice_status ) . "' )
65
+				AND 	posts.post_status 	IN ( '" . implode("','", $invoice_status) . "' )
66 66
 			";
67 67
 		}
68 68
 
69
-		if ( ! empty( $parent_invoice_status ) ) {
70
-			if ( ! empty( $invoice_status ) ) {
71
-				$query['where'] .= " AND ( parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) OR parent.ID IS NULL ) ";
69
+		if (!empty($parent_invoice_status)) {
70
+			if (!empty($invoice_status)) {
71
+				$query['where'] .= " AND ( parent.post_status IN ( '" . implode("','", $parent_invoice_status) . "' ) OR parent.ID IS NULL ) ";
72 72
 			} else {
73
-				$query['where'] .= " AND parent.post_status IN ( '" . implode( "','", $parent_invoice_status ) . "' ) ";
73
+				$query['where'] .= " AND parent.post_status IN ( '" . implode("','", $parent_invoice_status) . "' ) ";
74 74
 			}
75 75
 		}
76 76
 
77
-		if ( ! empty( $filter_range['before'] ) ) {
77
+		if (!empty($filter_range['before'])) {
78 78
 			$query['where'] .= "
79
-				AND 	posts.post_date <= '" . gmdate( 'Y-m-d 23:59:59', strtotime( $filter_range['before'] ) ) . "'
79
+				AND 	posts.post_date <= '" . gmdate('Y-m-d 23:59:59', strtotime($filter_range['before'])) . "'
80 80
 			";
81 81
 		}
82 82
 
83
-		if ( ! empty( $filter_range['after'] ) ) {
83
+		if (!empty($filter_range['after'])) {
84 84
 			$query['where'] .= "
85
-				AND 	posts.post_date >= '" . gmdate( 'Y-m-d 00:00:00', strtotime( $filter_range['after'] ) ) . "'
85
+				AND 	posts.post_date >= '" . gmdate('Y-m-d 00:00:00', strtotime($filter_range['after'])) . "'
86 86
 			";
87 87
 		}
88 88
 
89
-		if ( ! empty( $where ) ) {
89
+		if (!empty($where)) {
90 90
 
91
-			foreach ( $where as $value ) {
91
+			foreach ($where as $value) {
92 92
 
93
-				if ( strtolower( $value['operator'] ) === 'in' || strtolower( $value['operator'] ) === 'not in' ) {
93
+				if (strtolower($value['operator']) === 'in' || strtolower($value['operator']) === 'not in') {
94 94
 
95
-					if ( is_array( $value['value'] ) ) {
96
-						$value['value'] = implode( "','", $value['value'] );
95
+					if (is_array($value['value'])) {
96
+						$value['value'] = implode("','", $value['value']);
97 97
 					}
98 98
 
99
-					if ( ! empty( $value['value'] ) ) {
99
+					if (!empty($value['value'])) {
100 100
 						$where_value = "{$value['operator']} ('{$value['value']}')";
101 101
 					}
102 102
 				} else {
103 103
 					$where_value = "{$value['operator']} '{$value['value']}'";
104 104
 				}
105 105
 
106
-				if ( ! empty( $where_value ) ) {
106
+				if (!empty($where_value)) {
107 107
 					$query['where'] .= " AND {$value['key']} {$where_value}";
108 108
 				}
109 109
 			}
110 110
 		}
111 111
 
112
-		if ( $group_by ) {
112
+		if ($group_by) {
113 113
 			$query['group_by'] = "GROUP BY {$group_by}";
114 114
 		}
115 115
 
116
-		if ( $order_by ) {
116
+		if ($order_by) {
117 117
 			$query['order_by'] = "ORDER BY {$order_by}";
118 118
 		}
119 119
 
120
-		if ( $limit ) {
120
+		if ($limit) {
121 121
 			$query['limit'] = "LIMIT {$limit}";
122 122
 		}
123 123
 
124
-		$query = apply_filters( 'getpaid_reports_get_invoice_report_query', $query, $data );
125
-		$query = implode( ' ', $query );
124
+		$query = apply_filters('getpaid_reports_get_invoice_report_query', $query, $data);
125
+		$query = implode(' ', $query);
126 126
 
127
-		return self::execute( $query_type, $query );
127
+		return self::execute($query_type, $query);
128 128
 
129 129
 	}
130 130
 
@@ -135,26 +135,26 @@  discard block
 block discarded – undo
135 135
 	 * @param  array $data
136 136
 	 * @return array
137 137
 	 */
138
-	public static function prepare_invoice_data( $data ) {
138
+	public static function prepare_invoice_data($data) {
139 139
 
140 140
 		$prepared = array();
141 141
 
142
-		foreach ( $data as $raw_key => $value ) {
143
-			$key      = sanitize_key( $raw_key );
142
+		foreach ($data as $raw_key => $value) {
143
+			$key      = sanitize_key($raw_key);
144 144
 			$distinct = '';
145 145
 
146
-			if ( isset( $value['distinct'] ) ) {
146
+			if (isset($value['distinct'])) {
147 147
 				$distinct = 'DISTINCT';
148 148
 			}
149 149
 
150
-			$get_key = self::get_invoice_table_key( $key, $value['type'] );
150
+			$get_key = self::get_invoice_table_key($key, $value['type']);
151 151
 
152
-			if ( false === $get_key ) {
152
+			if (false === $get_key) {
153 153
 				// Skip to the next foreach iteration else the query will be invalid.
154 154
 				continue;
155 155
 			}
156 156
 
157
-			if ( ! empty( $value['function'] ) ) {
157
+			if (!empty($value['function'])) {
158 158
 				$get = "{$value['function']}({$distinct} {$get_key})";
159 159
 			} else {
160 160
 				$get = "{$distinct} {$get_key}";
@@ -175,22 +175,22 @@  discard block
 block discarded – undo
175 175
 	 * @param  bool $with_parent
176 176
 	 * @return array
177 177
 	 */
178
-	public static function prepare_invoice_joins( $data, $with_parent ) {
178
+	public static function prepare_invoice_joins($data, $with_parent) {
179 179
 		global $wpdb;
180 180
 
181 181
 		$prepared = array();
182 182
 
183
-		foreach ( $data as $raw_key => $value ) {
184
-			$join_type = isset( $value['join_type'] ) ? $value['join_type'] : 'INNER';
185
-			$type      = isset( $value['type'] ) ? $value['type'] : false;
186
-			$key       = sanitize_key( $raw_key );
183
+		foreach ($data as $raw_key => $value) {
184
+			$join_type = isset($value['join_type']) ? $value['join_type'] : 'INNER';
185
+			$type      = isset($value['type']) ? $value['type'] : false;
186
+			$key       = sanitize_key($raw_key);
187 187
 
188
-			switch ( $type ) {
188
+			switch ($type) {
189 189
 				case 'meta':
190
-					$prepared[ "meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS meta_{$key} ON ( posts.ID = meta_{$key}.post_id AND meta_{$key}.meta_key = '{$raw_key}' )";
190
+					$prepared["meta_{$key}"] = "{$join_type} JOIN {$wpdb->postmeta} AS meta_{$key} ON ( posts.ID = meta_{$key}.post_id AND meta_{$key}.meta_key = '{$raw_key}' )";
191 191
 					break;
192 192
 				case 'parent_meta':
193
-					$prepared[ "parent_meta_{$key}" ] = "{$join_type} JOIN {$wpdb->postmeta} AS parent_meta_{$key} ON (posts.post_parent = parent_meta_{$key}.post_id) AND (parent_meta_{$key}.meta_key = '{$raw_key}')";
193
+					$prepared["parent_meta_{$key}"] = "{$join_type} JOIN {$wpdb->postmeta} AS parent_meta_{$key} ON (posts.post_parent = parent_meta_{$key}.post_id) AND (parent_meta_{$key}.meta_key = '{$raw_key}')";
194 194
 					break;
195 195
 				case 'invoice_data':
196 196
 					$prepared['invoices'] = "{$join_type} JOIN {$wpdb->prefix}getpaid_invoices AS invoices ON posts.ID = invoices.post_id";
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
 			}
202 202
 		}
203 203
 
204
-		if ( $with_parent ) {
204
+		if ($with_parent) {
205 205
 			$prepared['parent'] = "LEFT JOIN {$wpdb->posts} AS parent ON posts.post_parent = parent.ID";
206 206
 		}
207 207
 
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
 	 * @param  string $table
218 218
 	 * @return string|false
219 219
 	 */
220
-	public static function get_invoice_table_key( $key, $table ) {
220
+	public static function get_invoice_table_key($key, $table) {
221 221
 
222 222
 		$keys = array(
223 223
 			'meta'         => "meta_{$key}.meta_value",
@@ -227,7 +227,7 @@  discard block
 block discarded – undo
227 227
 			'invoice_item' => "invoice_items.{$key}",
228 228
 		);
229 229
 
230
-		return isset( $keys[ $table ] ) ? $keys[ $table ] : false;
230
+		return isset($keys[$table]) ? $keys[$table] : false;
231 231
 
232 232
 	}
233 233
 
@@ -239,16 +239,16 @@  discard block
 block discarded – undo
239 239
 	 * @param  string $query
240 240
 	 * @return mixed depending on query_type
241 241
 	 */
242
-	public static function execute( $query_type, $query ) {
242
+	public static function execute($query_type, $query) {
243 243
 		global $wpdb;
244 244
 
245
-		$query_hash = md5( $query_type . $query );
246
-		$result     = self::get_cached_query( $query_hash );
247
-		if ( $result === false ) {
245
+		$query_hash = md5($query_type . $query);
246
+		$result     = self::get_cached_query($query_hash);
247
+		if ($result === false) {
248 248
 			self::enable_big_selects();
249 249
 
250
-			$result = $wpdb->$query_type( $query );
251
-			self::set_cached_query( $query_hash, $result );
250
+			$result = $wpdb->$query_type($query);
251
+			self::set_cached_query($query_hash, $result);
252 252
 		}
253 253
 
254 254
 		return $result;
@@ -263,8 +263,8 @@  discard block
 block discarded – undo
263 263
 
264 264
 		global $wpdb;
265 265
 
266
-		if ( ! $big_selects ) {
267
-			$wpdb->query( 'SET SESSION SQL_BIG_SELECTS=1' );
266
+		if (!$big_selects) {
267
+			$wpdb->query('SET SESSION SQL_BIG_SELECTS=1');
268 268
 			$big_selects = true;
269 269
 		}
270 270
 	}
@@ -276,11 +276,11 @@  discard block
 block discarded – undo
276 276
 	 *
277 277
 	 * @return mixed|false The cache contents on success, false on failure to retrieve contents.
278 278
 	 */
279
-	protected static function get_cached_query( $query_hash ) {
279
+	protected static function get_cached_query($query_hash) {
280 280
 
281 281
 		return wp_cache_get(
282 282
 			$query_hash,
283
-			strtolower( __CLASS__ )
283
+			strtolower(__CLASS__)
284 284
 		);
285 285
 
286 286
 	}
@@ -291,12 +291,12 @@  discard block
 block discarded – undo
291 291
 	 * @param string $query_hash The query hash.
292 292
 	 * @param mixed  $data The data to cache.
293 293
 	 */
294
-	protected static function set_cached_query( $query_hash, $data ) {
294
+	protected static function set_cached_query($query_hash, $data) {
295 295
 
296 296
 		wp_cache_set(
297 297
 			$query_hash,
298 298
 			$data,
299
-			strtolower( __CLASS__ ),
299
+			strtolower(__CLASS__),
300 300
 			MINUTE_IN_SECONDS
301 301
 		);
302 302
 
Please login to merge, or discard this patch.