Completed
Push — hotfix/cli-generate-donor ( f42cef...baf467 )
by Ravinder
05:57 queued 02:04
created

GIVE_CLI_COMMAND::get_random_name()   A

Complexity

Conditions 2

Size

Total Lines 47
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 30
nop 0
dl 0
loc 47
rs 9.0303
c 0
b 0
f 0
1
<?php
2
/**
3
 * GIVE WP_CLI commands
4
 *
5
 * @package give
6
 * @since   1.7
7
 */
8
9
// Exit if accessed directly.
10
if ( ! defined( 'ABSPATH' ) ) {
11
	exit;
12
}
13
14
// Add give command.
15
WP_CLI::add_command( 'give', 'GIVE_CLI_COMMAND' );
16
17
18
/**
19
 * Work with Give through WP-CLI
20
 *
21
 * Adds CLI support to Give through WP-CLI
22
 *
23
 * @since 1.7
24
 */
25
class GIVE_CLI_COMMAND {
26
27
	/**
28
	 * This param uses to count process/step inside loop.
29
	 *
30
	 * @var int $counter Counter.
31
	 */
32
	private static $counter;
33
34
	/**
35
	 * This helps to get information give plugin data.
36
	 *
37
	 * @var Give_API Object.
38
	 */
39
	private $api;
40
41
42
	/**
43
	 * GIVE_CLI_Command constructor.
44
	 */
45
	public function __construct() {
46
		$this->api = new Give_API();
47
	}
48
49
50
	/**
51
	 * Get Give logo
52
	 *
53
	 * ## OPTIONS
54
	 *
55
	 * None. for a fun surprise.
56
	 *
57
	 * ## EXAMPLES
58
	 *
59
	 * wp give logo
60
	 *
61
	 * @since         1.7
62
	 * @access        public
63
	 *
64
	 * @param        string $args       Command Data.
65
	 * @param        array  $assoc_args List of command data.
66
	 *
67
	 * @return        void
68
	 *
69
	 * @subcommand    logo
70
	 */
71
	public function ascii( $args, $assoc_args ) {
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $assoc_args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
72
		WP_CLI::log( file_get_contents( GIVE_PLUGIN_DIR . 'assets/images/give-ascii-logo.txt' ) );
0 ignored issues
show
introduced by
file_get_contents is highly discouraged, please use wpcom_vip_file_get_contents() instead.
Loading history...
73
	}
74
75
76
	/**
77
	 * Get Give details
78
	 *
79
	 * ## OPTIONS
80
	 *
81
	 * None. Returns basic info regarding your Give instance.
82
	 *
83
	 * ## EXAMPLES
84
	 *
85
	 * wp give details
86
	 *
87
	 * @since         1.7
88
	 * @access        public
89
	 *
90
	 * @param        string $args       Command Data.
91
	 * @param        array  $assoc_args List of command data.
92
	 *
93
	 * @return        void
94
	 *
95
	 * @subcommand    details
96
	 */
97
	public function details( $args, $assoc_args ) {
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $assoc_args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
98
99
		/**
100
		 * Plugin Information
101
		 */
102
		WP_CLI::log( $this->color_message( __( 'Give Version: ', 'give' ) ) . GIVE_VERSION );
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'GIVE_VERSION'
Loading history...
103
104
		/**
105
		 * General Information.
106
		 */
107
		WP_CLI::log( "\n####   " . $this->color_message( __( 'General information', 'give' ) ) . '   ####' );
108
109
		$success_page = give_get_option( 'success_page' );
110
		$failure_page = give_get_option( 'failure_page' );
111
		$history_page = give_get_option( 'history_page' );
112
113
		WP_CLI::log( $this->color_message( sprintf( __( 'Success Page: ', 'give' ) ) ) . ( $success_page ? "[{$success_page}] " . get_permalink( $success_page ) : __( 'Not Set', 'give' ) ) );
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '('
Loading history...
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'get_permalink'
Loading history...
114
		WP_CLI::log( $this->color_message( __( 'Failed Donation Page: ', 'give' ) ) . ( $failure_page ? "[{$failure_page}] " . get_permalink( $failure_page ) : __( 'Not Set', 'give' ) ) );
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '('
Loading history...
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'get_permalink'
Loading history...
115
		WP_CLI::log( $this->color_message( __( 'Donation History Page: ', 'give' ) ) . ( $history_page ? "[{$history_page}] " . get_permalink( $history_page ) : __( 'Not Set', 'give' ) ) );
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '('
Loading history...
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'get_permalink'
Loading history...
116
		WP_CLI::log( $this->color_message( __( 'Country: ', 'give' ) ) . give_get_country() );
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'give_get_country'
Loading history...
117
118
		/**
119
		 * Currency Information.
120
		 */
121
		$default_gateway = give_get_option( 'default_gateway' );
122
123
		WP_CLI::log( "\n####   " . $this->color_message( __( 'Currency Information', 'give' ) ) . '   ####' );
124
125
		WP_CLI::log( $this->color_message( __( 'Currency: ', 'give' ), give_get_currency() ) );
126
		WP_CLI::log( $this->color_message( __( 'Currency Position: ', 'give' ), give_get_currency_position() ) );
127
		WP_CLI::log( $this->color_message( __( 'Thousand Separator: ', 'give' ), give_get_price_thousand_separator() ) );
128
		WP_CLI::log( $this->color_message( __( 'Decimal Separator: ', 'give' ), give_get_price_decimal_separator() ) );
129
		WP_CLI::log( $this->color_message( __( 'Number of Decimals: ', 'give' ), give_get_price_decimals() ) );
130
		WP_CLI::log( $this->color_message( __( 'Test Mode: ', 'give' ), ( give_get_option( 'test_mode' ) ? __( 'Yes', 'give' ) : __( 'No', 'give' ) ) ) );
131
		WP_CLI::log( $this->color_message( __( 'Default Gateway: ', 'give' ), ( $default_gateway ? $default_gateway : __( 'Not Set', 'give' ) ) ) );
132
133
		// Payment gateways Information.
134
		$gateways = give_get_ordered_payment_gateways( give_get_payment_gateways() );
135
		WP_CLI::log( $this->color_message( __( 'Enabled Gateways: ', 'give' ) ) );
136
137
		if ( ! empty( $gateways ) ) {
138
			self::$counter = 1;
139
			foreach ( $gateways as $gateway ) {
140
				WP_CLI::log( '  ' . $this->color_message( self::$counter, $gateway['admin_label'] ) );
141
				self::$counter ++;
142
			}
143
		} else {
144
			WP_CLI::log( __( 'Not any payment gateways found', 'give' ) );
145
		}
146
	}
147
148
149
	/**
150
	 * Get the forms currently posted on your Give site
151
	 *
152
	 * ## OPTIONS
153
	 *
154
	 * [--id=<form_id>]
155
	 * : A specific form ID to retrieve
156
	 *
157
	 * [--number=<form_count>]
158
	 * : Number of form to retrieve
159
	 *
160
	 * ## EXAMPLES
161
	 *
162
	 * wp give forms
163
	 * wp give forms --id=103
164
	 * wp give forms --number=103
165
	 *
166
	 * @since         1.7
167
	 * @access        public
168
	 *
169
	 * @param        string $args       Command Data.
170
	 * @param        array  $assoc_args List of command data.
171
	 *
172
	 * @return        void
173
	 *
174
	 * @subcommand    forms
175
	 */
176
	public function forms( $args, $assoc_args ) {
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
177
		global $wp_query;
178
		$form_id = isset( $assoc_args ) && array_key_exists( 'id', $assoc_args ) ? absint( $assoc_args['id'] ) : false;
179
		$number  = isset( $assoc_args ) && array_key_exists( 'number', $assoc_args ) ? absint( $assoc_args['number'] ) : 10;
180
		$start   = time();
0 ignored issues
show
Unused Code introduced by
$start is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
181
182
		// Cache previous number query var.
183
		$is_set_number = $cache_per_page = false;
184 View Code Duplication
		if ( isset( $wp_query->query_vars['number'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
185
			$cache_per_page = $wp_query->query_vars['number'];
186
			$is_set_number  = true;
187
		}
188
189
		// Change number query var.
190
		$wp_query->query_vars['number'] = $number;
191
192
		// Get forms.
193
		$forms = $form_id ? $this->api->get_forms( $form_id ) : $this->api->get_forms();
194
195
		// Reset number query var.
196
		if ( $is_set_number ) {
197
			$wp_query->query_vars['number'] = $cache_per_page;
198
		}
199
200
		// Bailout.
201
		if ( array_key_exists( 'error', $forms ) ) {
202
203
			WP_CLI::warning( $forms['error'] );
204
205
			return;
206
		} elseif ( empty( $forms['forms'] ) ) {
207
208
			WP_CLI::error( __( 'No forms found.', 'give' ) );
209
210
			return;
211
		}
212
213
		// Param to check if form typeis already showed or not.
214
		$is_show_form_type = false;
215
216
		if ( 1 === count( $forms ) && $form_id ) {
217
			// Show single form.
218
			foreach ( $forms['forms'][0] as $key => $info ) {
219
				switch ( $key ) {
220
					case 'stats':
221
						$this->color_main_heading( ucfirst( $key ) );
222
223
						foreach ( $info as $heading => $data ) {
224
							$this->color_sub_heading( ucfirst( $heading ) );
225
							switch ( $heading ) {
226
								default:
0 ignored issues
show
Unused Code introduced by
default: foreach ($d...data)); } } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
227
									foreach ( $data as $subheading => $subdata ) {
228
229
										switch ( $subheading ) {
230
											case 'earnings':
231
												WP_CLI::log( $this->color_message( $subheading . ': ', give_currency_filter( $subdata ) ) );
232
												break;
233
											default:
234
												WP_CLI::log( $this->color_message( $subheading . ': ', $subdata ) );
235
										}
236
									}
237
							}
238
						}
239
						break;
240
241
					case 'pricing':
242
					case 'info':
243
					default:
244
						$this->color_main_heading( ucfirst( $key ) );
245
246
						// Show form type.
247
						if ( ! $is_show_form_type ) {
248
							$form              = new Give_Donate_Form( $form_id );
249
							$is_show_form_type = true;
250
251
							WP_CLI::log( $this->color_message( __( 'form type', 'give' ), $form->get_type() ) );
252
						}
253
254
						foreach ( $info as $heading => $data ) {
255
256
							switch ( $heading ) {
257
								case 'id':
258
									WP_CLI::log( $this->color_message( $heading, $data ) );
259
									break;
260
261
								default:
262
									$data = empty( $data ) ? __( 'Not set', 'give' ) : $data;
263
									WP_CLI::log( $this->color_message( $heading, $data ) );
264
							}
265
						}
266
				}// End switch().
267
			}// End foreach().
268
		} else {
269
			// Show multiple form.
270
			$table_data             = array();
271
			$is_table_first_row_set = false;
272
			$table_column_count     = 0;
0 ignored issues
show
Unused Code introduced by
$table_column_count is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
273
274
			WP_CLI::line( $this->color_message( sprintf( __( '%d donation forms found', 'give' ), count( $forms['forms'] ) ), '', false ) );
275
276
			foreach ( $forms['forms'] as $index => $form_data ) {
277
278
				// Default table data.
279
				$table_first_row = array();
280
				$table_row       = array();
281
282
				foreach ( $form_data['info'] as $key => $form ) {
283
284
					// Do not show thumbnail, content and link in table.
285
					if ( in_array( $key, array( 'content', 'thumbnail', 'link' ), true ) ) {
286
						continue;
287
					}
288
289
					if ( ! $is_table_first_row_set ) {
290
						$table_first_row[] = $key;
291
					}
292
293
					$table_row[] = $form;
294
295
					if ( 'status' === $key ) {
296
						// First array item will be an form id in our case.
297
						$form = new Give_Donate_Form( absint( $table_row[0] ) );
298
299
						$table_row[] = $form->get_type();
300
					}
301
				}
302
303
				// Set table first row.
304
				if ( ! $is_table_first_row_set ) {
305
306
					// Add extra column to table.
307
					$table_first_row[] = 'type';
308
309
					$table_data[]           = $table_first_row;
310
					$is_table_first_row_set = true;
311
				}
312
313
				// set table data.
314
				$table_data[] = $table_row;
315
			}// End foreach().
316
317
			$this->display_table( $table_data );
318
		}// End if().
319
	}
320
321
322
	/**
323
	 * Get the donors currently on your Give site. Can also be used to create donors records
324
	 *
325
	 * ## OPTIONS
326
	 *
327
	 * [--id=<donor_id>]
328
	 * : A specific donor ID to retrieve
329
	 *
330
	 * [--email=<donor_email>]
331
	 * : The email address of the donor to retrieve
332
	 *
333
	 * [--number=<donor_count>]
334
	 * : The number of donor to retrieve
335
	 *
336
	 * [--create=<number>]
337
	 * : The number of arbitrary donors to create. Leave as 1 or blank to create a
338
	 * donor with a specific email
339
	 *
340
	 * [--form-id=<donation_form_id>]
341
	 * : Get list of donors of specific donation form
342
	 *
343
	 * [--name=<name_of_donor>]
344
	 * : Name with which you want to create new donor
345
	 *
346
	 * [--format=<output_format>]
347
	 * : In which format you want to see results. Valid formats: table, json, csv
348
	 *
349
	 * ## EXAMPLES
350
	 *
351
	 * wp give donors
352
	 * wp give donors --id=103
353
	 * wp give donors [email protected]
354
	 * wp give donors --create=1 [email protected]
355
	 * wp give donors --create=1 [email protected] --name="John Doe"
356
	 * wp give donors --create=1000
357
	 * wp give donors --number=1000
358
	 * wp give donors --form-id=1024
359
	 *
360
	 * @since         1.7
361
	 * @access        public
362
	 *
363
	 * @param        string $args       Command Data.
364
	 * @param        array  $assoc_args List of command data.
365
	 *
366
	 * @return        void
367
	 *
368
	 * @subcommand    donors
369
	 */
370
	public function donors( $args, $assoc_args ) {
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
371
		global $wp_query;
372
		$donor_id = isset( $assoc_args ) && array_key_exists( 'id', $assoc_args ) ? absint( $assoc_args['id'] ) : false;
373
		$email    = isset( $assoc_args ) && array_key_exists( 'email', $assoc_args ) ? $assoc_args['email'] : false;
374
		$name     = isset( $assoc_args ) && array_key_exists( 'name', $assoc_args ) ? $assoc_args['name'] : '';
375
		$create   = isset( $assoc_args ) && array_key_exists( 'create', $assoc_args ) ? $assoc_args['create'] : false;
376
		$number   = isset( $assoc_args ) && array_key_exists( 'number', $assoc_args ) ? $assoc_args['number'] : 10;
377
		$form_id  = isset( $assoc_args ) && array_key_exists( 'form-id', $assoc_args ) ? $assoc_args['form-id'] : 0;
378
		$format   = isset( $assoc_args ) && array_key_exists( 'format', $assoc_args ) ? $assoc_args['format'] : 'table';
379
		$start    = time();
380
381
		if ( $create ) {
382
			$number = 1;
383
384
			if ( isset( $assoc_args['email'] ) && ! is_email( $email ) ) {
385
				WP_CLI::warning( 'Wrong email address provided.', 'give' );
386
387
				return;
388
			}
389
390
			// Create one or more donors.
391
			if ( ! $email ) {
392
				// If no email is specified, look to see if we are generating arbitrary donor accounts.
393
				$number = is_numeric( $create ) ? absint( $create ) : 1;
394
			}
395
396
			for ( $i = 0; $i < $number; $i ++ ) {
397
				if ( ! $email ) {
398
399
					// Generate fake email.
400
					$email = 'customer-' . uniqid() . '@test.com';
401
				}
402
403
				$args = array(
404
					'email' => $email,
405
					'name'  => $name,
406
				);
407
408
				$donor_id = Give()->donors->add( $args );
409
410
				if ( $donor_id ) {
411
					WP_CLI::line( $this->color_message( sprintf( __( 'Donor #%d created successfully', 'give' ), $donor_id ) ) );
412
				} else {
413
					WP_CLI::error( __( 'Failed to create donor', 'give' ) );
414
				}
415
416
				// Reset email to false so it is generated on the next loop (if creating donors).
417
				$email = false;
418
			}
419
420
			WP_CLI::line( $this->color_message( sprintf( __( '%1$d donors created in %2$d seconds', 'give' ), $number, time() - $start ) ) );
421
422
		} else {
423
			// Counter.
424
			self::$counter = 1;
425
426
			// Search for customers.
427
			$search = $donor_id ? $donor_id : $email;
428
429
			/**
430
			 * Get donors.
431
			 */
432
			// Cache previous number query var.
433
			$is_set_number = $cache_per_page = false;
434 View Code Duplication
			if ( isset( $wp_query->query_vars['number'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
435
				$cache_per_page = $wp_query->query_vars['number'];
436
				$is_set_number  = true;
437
			}
438
439
			// Change number query var.
440
			$wp_query->query_vars['number'] = $number;
441
442
			// Get donors.
443
			if ( $form_id ) {
444
				// @TODO: Allow user to get a list of donors by donation status.
445
				$donors = $this->get_donors_by_form_id( $form_id );
446
			} else {
447
				$donors = $this->api->get_donors( $search );
448
			}
449
450
			// Reset number query var.
451
			if ( $is_set_number ) {
452
				$wp_query->query_vars['number'] = $cache_per_page;
453
			}
454
455
			if ( isset( $donors['error'] ) ) {
456
				WP_CLI::error( $donors['error'] );
457
			}
458
459
			if ( empty( $donors ) ) {
460
				WP_CLI::error( __( 'No donors found.', 'give' ) );
461
462
				return;
463
			}
464
465
			$table_data             = array();
466
			$is_table_first_row_set = false;
467
468
			foreach ( $donors['donors'] as $donor_data ) {
469
				// Set default table row data.
470
				$table_first_row = array( __( 's_no', 'give' ) );
471
				$table_row       = array( self::$counter );
472
473
				foreach ( $donor_data as $key => $donor ) {
474
					switch ( $key ) {
475
						case 'stats':
476
							foreach ( $donor as $heading => $data ) {
477
478
								// Get first row.
479
								if ( ! $is_table_first_row_set ) {
480
									$table_first_row[] = $heading;
481
								}
482
483
								switch ( $heading ) {
484
									case 'total_spent':
485
										$table_row[] = give_currency_filter( $data );
486
										break;
487
488
									default:
489
										$table_row[] = $data;
490
								}
491
							}
492
							break;
493
494
						case 'info':
495
						default:
496
							foreach ( $donor as $heading => $data ) {
497
498
								// Get first row.
499
								if ( ! $is_table_first_row_set ) {
500
									$table_first_row[] = $heading;
501
								}
502
503
								$table_row[] = $data;
504
							}
505
					}
506
				}
507
508
				// Add first row data to table data.
509
				if ( ! $is_table_first_row_set ) {
510
					$table_data[]           = $table_first_row;
511
					$is_table_first_row_set = true;
512
				}
513
514
				// Add table row data.
515
				$table_data[] = $table_row;
516
517
				// Increase counter.
518
				self::$counter ++;
519
			}// End foreach().
520
521
			switch ( $format ) {
522
				case 'json':
523
					$table_column_name = $table_data[0];
524
					unset( $table_data[0] );
525
526
					$new_table_data = array();
527
					foreach ( $table_data as $index => $data ) {
528
						foreach ( $data as $key => $value ) {
529
							$new_table_data[ $index ][ $table_column_name[ $key ] ] = $value;
530
						}
531
					}
532
533
					WP_CLI::log( json_encode( $new_table_data ) );
534
					break;
535
536
				case 'csv':
537
					$file_path = trailingslashit( WP_CONTENT_DIR ) . 'uploads/give_donors_' . date( 'Y_m_d_s', current_time( 'timestamp' ) ) . '.csv';
538
					$fp        = fopen( $file_path, 'w' );
539
540
					if ( is_writable( $file_path ) ) {
0 ignored issues
show
introduced by
Filesystem writes are forbidden, you should not be using is_writable()
Loading history...
541
						foreach ( $table_data as $fields ) {
542
							fputcsv( $fp, $fields );
0 ignored issues
show
introduced by
Filesystem writes are forbidden, you should not be using fputcsv()
Loading history...
543
						}
544
545
						fclose( $fp );
546
547
						WP_CLI::success( "Donors list csv created successfully: {$file_path}" );
548
					} else {
549
						WP_CLI::warning( "Unable to create donors list csv file: {$file_path} (May folder do not have write permission)" );
550
					}
551
552
					break;
553
554
				default:
555
					$this->display_table( $table_data );
556
			}// End switch().
557
		}// End if().
558
	}
559
560
561
	/**
562
	 * Get the recent donations for your Give site
563
	 *
564
	 * ## OPTIONS
565
	 *
566
	 * [--number=<donation_count>]
567
	 * : The number of donations to retrieve
568
	 *
569
	 *
570
	 * ## EXAMPLES
571
	 *
572
	 * wp give donations
573
	 * wp give donations --number=100
574
	 *
575
	 * @since         1.7
576
	 * @access        public
577
	 *
578
	 * @param        string $args       Command Data.
579
	 * @param        array  $assoc_args List of command data.
580
	 *
581
	 * @return        void
582
	 *
583
	 * @subcommand    donations
584
	 */
585
	public function donations( $args, $assoc_args ) {
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
586
		global $wp_query;
587
		$number = isset( $assoc_args ) && array_key_exists( 'number', $assoc_args ) ? $assoc_args['number'] : 10;
588
589
		// Cache previous number query var.
590
		$is_set_number = $cache_per_page = false;
591 View Code Duplication
		if ( isset( $wp_query->query_vars['number'] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
592
			$cache_per_page = $wp_query->query_vars['number'];
593
			$is_set_number  = true;
594
		}
595
596
		// Change number query var.
597
		$wp_query->query_vars['number'] = $number;
598
599
		// Get donations.
600
		$donations = $this->api->get_recent_donations();
601
602
		// Reset number query var.
603
		if ( $is_set_number ) {
604
			$wp_query->query_vars['number'] = $cache_per_page;
605
		}
606
607
		if ( empty( $donations ) ) {
608
			WP_CLI::error( __( 'No donations found.', 'give' ) );
609
610
			return;
611
		}
612
613
		self::$counter = 1;
614
615
		foreach ( $donations['donations'] as $key => $donation ) {
616
			$this->color_main_heading( sprintf( __( '%1$s. Donation #%2$s', 'give' ), self::$counter, $donation['ID'] ), 'Y' );
617
			self::$counter ++;
618
619
			foreach ( $donation as $column => $data ) {
620
621
				if ( is_array( $data ) ) {
622
					$this->color_sub_heading( $column );
623
					foreach ( $data as $subcolumn => $subdata ) {
624
625
						// Decode html codes.
626
						switch ( $subcolumn ) {
627
							case 'name':
628
								$subdata = html_entity_decode( $subdata );
629
								break;
630
						}
631
632
						// @TODO Check if multi dimension array information is importent to show or not. For example inside donation array we have array for fees data inside payment meta.
633
						if ( is_array( $subdata ) ) {
634
							continue;
635
						}
636
637
						WP_CLI::log( $this->color_message( $subcolumn, $subdata ) );
638
					}
639
					continue;
640
				}
641
642
				WP_CLI::log( $this->color_message( $column, $data ) );
643
			}
644
		}
645
	}
646
647
	/**
648
	 * Get give plugin report.
649
	 *
650
	 * ## OPTIONS
651
	 *
652
	 * [--id=<donation_form_id>]
653
	 * : The ID of a specific donation_form to retrieve stats for, or all
654
	 *
655
	 * [--date=<range|this_month|last_month|today|yesterday|this_quarter|last_quarter|this_year|last_year>]
656
	 * : A specific date range to retrieve stats for
657
	 *
658
	 * [--start-date=<date>]
659
	 * : The start date of a date range to retrieve stats for
660
	 *
661
	 * [--end-date=<date>]
662
	 * : The end date of a date range to retrieve stats for
663
	 *
664
	 * ## EXAMPLES
665
	 *
666
	 * wp give report
667
	 * wp give report --date=this_month
668
	 * wp give report --start-date=01/02/2014 --end-date=02/23/2014
669
	 * wp give report --date=last_year
670
	 * wp give report --date=last_year --id=15
671
	 *
672
	 * @since         1.7
673
	 * @access        public
674
	 *
675
	 * @param        string $args       Command Data.
676
	 * @param        array  $assoc_args List of command data.
677
	 *
678
	 * @subcommand    report
679
	 *
680
	 * @return        void
681
	 */
682
	public function report( $args, $assoc_args ) {
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
683
		$stats      = new Give_Payment_Stats();
684
		$date       = isset( $assoc_args ) && array_key_exists( 'date', $assoc_args ) ? $assoc_args['date'] : false;
685
		$start_date = isset( $assoc_args ) && array_key_exists( 'start-date', $assoc_args ) ? $assoc_args['start-date'] : false;
686
		$end_date   = isset( $assoc_args ) && array_key_exists( 'end-date', $assoc_args ) ? $assoc_args['end-date'] : false;
687
		$form_id    = isset( $assoc_args ) && array_key_exists( 'id', $assoc_args ) ? $assoc_args['id'] : 0;
688
689
		if ( ! empty( $date ) ) {
690
			$start_date = $date;
691
			$end_date   = false;
692
		} elseif ( empty( $date ) && empty( $start_date ) ) {
693
			$start_date = 'this_month';
694
			$end_date   = false;
695
		}
696
697
		// Get stats.
698
		$earnings = $stats->get_earnings( $form_id, $start_date, $end_date );
699
		$sales    = $stats->get_sales( $form_id, $start_date, $end_date );
700
701
		WP_CLI::line( $this->color_message( __( 'Earnings', 'give' ), give_currency_filter( $earnings ) ) );
702
		WP_CLI::line( $this->color_message( __( 'Sales', 'give' ), $sales ) );
703
	}
704
705
706
	/**
707
	 * Delete cache (transient).
708
	 *
709
	 * ## OPTIONS
710
	 *
711
	 * --action=<cache_action>
712
	 * : Value of this parameter can be delete (in case you want to delete all stat cache).
713
	 *
714
	 * ## EXAMPLES
715
	 *
716
	 *    # See form report
717
	 *    wp give cache --action=delete
718
	 *
719
	 * @since         1.7
720
	 * @access        public
721
	 *
722
	 * @param        string $args       Command Data.
723
	 * @param        array  $assoc_args List of command data.
724
	 *
725
	 * @return        void
726
	 *
727
	 * @subcommand    cache
728
	 */
729
	public function cache( $args, $assoc_args ) {
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
730
		$action = isset( $assoc_args ) && array_key_exists( 'action', $assoc_args ) ? $assoc_args['action'] : false;
731
732
		// Bailout.
733
		if ( ! $action || ! in_array( $action, array( 'delete' ), true ) ) {
734
			WP_CLI::warning( __( 'Type wp give cache --action=delete to delete all stat transients', 'give' ) );
735
736
			return;
737
		}
738
739
		switch ( $action ) {
740
			case 'delete' :
741
				// Reset counter.
742
				self::$counter = 1;
743
744
				if ( $this->delete_stats_transients() ) {
745
					// Report .eading.
746
					WP_CLI::success( 'Give cache deleted.' );
747
				} else {
748
					// Report .eading.
749
					WP_CLI::warning( 'We did not find any Give plugin cache to delete :)' );
750
				}
751
				break;
752
		}
753
754
	}
755
756
	/**
757
	 * Delete all form stat transient
758
	 *
759
	 * @since     1.7
760
	 * @access    private
761
	 *
762
	 * @return    bool
763
	 */
764
	private function delete_stats_transients() {
765
		global $wpdb;
766
767
		$stat_option_names = $wpdb->get_results(
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
768
			$wpdb->prepare(
769
				"SELECT option_name FROM {$wpdb->options} where (option_name LIKE '%%%s%%' OR option_name LIKE '%%%s%%')",
770
				array(
771
					'_transient_give_stats_',
772
					'give_cache',
773
				)
774
			),
775
			ARRAY_A
776
		);
777
778
		if ( ! empty( $stat_option_names ) ) {
779
780
			foreach ( $stat_option_names as $option_name ) {
781
				$error       = false;
0 ignored issues
show
Unused Code introduced by
$error is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
782
				$option_name = $option_name['option_name'];
783
784 View Code Duplication
				switch ( true ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
785
					case ( false !== strpos( $option_name, 'transient' ) ):
786
						$option_name = str_replace( '_transient_', '', $option_name );
787
						$error       = delete_transient( $option_name );
788
						break;
789
790
					default:
791
						$error = delete_option( $option_name );
792
				}
793
794
				if ( $error ) {
795
					WP_CLI::log( $this->color_message( self::$counter, $option_name ) );
796
					self::$counter ++;
797
				} else {
798
					WP_CLI::log( $this->color_message( __( 'Error while deleting this transient', 'give' ), $option_name ) );
799
				}
800
			}
801
802
			return true;
803
		}
804
805
		return false;
806
	}
807
808
809
	/**
810
	 * Return colored message
811
	 *
812
	 * @param    string $heading Message heading.
813
	 * @param    string $message Message content.
814
	 * @param    bool   $colon   Check if add colon between heading and message.
815
	 * @param    string $color   Heading color.
816
	 *
817
	 * @return   string
818
	 */
819
	private function color_message( $heading, $message = '', $colon = true, $color = 'g' ) {
820
		// Add colon.
821
		if ( $colon ) {
822
			$heading = $heading . ': ';
823
		}
824
825
		return WP_CLI::colorize( "%{$color}" . $heading . '%n' ) . $message;
826
	}
827
828
829
	/**
830
	 * Output section heading.
831
	 *
832
	 * @since     1.7
833
	 * @access    private
834
	 *
835
	 * @param    string $heading Heading.
836
	 * @param    string $color   Color.
837
	 *
838
	 * @return    void
839
	 */
840
	private function color_main_heading( $heading, $color = 'g' ) {
841
		WP_CLI::log( "\n######   " . $this->color_message( $heading, '', false, $color ) . '   ######' );
842
	}
843
844
	/**
845
	 * Output section sub heading.
846
	 *
847
	 * @since     1.7
848
	 * @access    private
849
	 *
850
	 * @param    string $subheading Sub heading.
851
	 *
852
	 * @return    void
853
	 */
854
	private function color_sub_heading( $subheading ) {
855
		WP_CLI::log( "\n--->" . $subheading . '', '', false );
856
	}
857
858
859
	/**
860
	 * Display data in table format.
861
	 *
862
	 * @since     1.7
863
	 * @access    private
864
	 *
865
	 * @param    array $data Array of table data.
866
	 *
867
	 * @return    void
868
	 */
869
	private function display_table( $data ) {
870
		$table = new \cli\Table();
871
872
		// Set table header.
873
		$table->setHeaders( $data[0] );
874
875
		// Remove table header.
876
		unset( $data[0] );
877
878
		// Set table data.
879
		$table->setRows( $data );
880
881
		// Display table.
882
		$table->display();
883
	}
884
885
886
	/**
887
	 * Get donors by form id.
888
	 *
889
	 * @since 1.8
890
	 *
891
	 * @param int $form_id From id.
892
	 *
893
	 * @return array
894
	 */
895
896
	private function get_donors_by_form_id( $form_id ) {
897
		$donors = array();
898
899
		$donations = new Give_Payments_Query(
900
			array(
901
				'give_forms' => array( $form_id ),
902
				'number'     => - 1,
903
				'status'     => array( 'publish' ),
904
			)
905
		);
906
907
		$donations   = $donations->get_payments();
908
		$skip_donors = array();
909
910
		/* @var Give_Payment|object $donation Payment object. */
911
		foreach ( $donations as $donation ) {
912
913
			if ( in_array( $donation->customer_id, $skip_donors ,true ) ) {
914
				continue;
915
			}
916
917
			if ( ! empty( $donors ) ) {
918
				$donors['donors'][] = current( current( $this->api->get_donors( (int) $donation->customer_id ) ) );
919
			} else {
920
				$donors = array_merge( $donors, $this->api->get_donors( (int) $donation->customer_id ) );
921
			}
922
923
			$skip_donors[] = $donation->customer_id;
924
		}
925
926
		return $donors;
927
	}
928
}
929