Completed
Push — issues/1796 ( fe0f55...71eafd )
by Ravinder
17:33
created

Give_Sales_Log_Table::column_default()   C

Complexity

Conditions 9
Paths 9

Size

Total Lines 49
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 30
nc 9
nop 2
dl 0
loc 49
rs 5.7446
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 28 and the first side effect is on line 13.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * Sales Log View Class
4
 *
5
 * @package     Give
6
 * @subpackage  Admin/Reports
7
 * @copyright   Copyright (c) 2016, WordImpress
8
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
9
 */
10
11
// Exit if accessed directly.
12
if ( ! defined( 'ABSPATH' ) ) {
13
	exit;
14
}
15
16
// Load WP_List_Table if not loaded
17
if ( ! class_exists( 'WP_List_Table' ) ) {
18
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
19
}
20
21
/**
22
 * Give_Sales_Log_Table Class
23
 *
24
 * Renders the sales log list table
25
 *
26
 * @since 1.0
27
 */
28
class Give_Sales_Log_Table extends WP_List_Table {
29
	/**
30
	 * Number of results to show per page
31
	 *
32
	 * @since 1.0
33
	 * @var int
34
	 */
35
	public $per_page = 30;
36
37
	/**
38
	 * Get things started
39
	 *
40
	 * @since 1.0
41
	 * @see   WP_List_Table::__construct()
42
	 */
43
	public function __construct() {
44
		global $status, $page;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
45
46
		// Set parent defaults
47
		parent::__construct( array(
48
			'singular' => give_get_forms_label_singular(),    // Singular name of the listed records
49
			'plural'   => give_get_forms_label_plural(),        // Plural name of the listed records
50
			'ajax'     => false,// Does this table support ajax?
51
		) );
52
53
		add_action( 'give_log_view_actions', array( $this, 'give_forms_filter' ) );
54
	}
55
56
	/**
57
	 * This function renders most of the columns in the list table.
58
	 *
59
	 * @access public
60
	 * @since  1.0
61
	 *
62
	 * @param array  $item        Contains all the data of the discount code
63
	 * @param string $column_name The name of the column
64
	 *
65
	 * @return string Column Name
66
	 */
67
	public function column_default( $item, $column_name ) {
68
69
		$payment = give_get_payment_by( 'id', $item['payment_id'] );
70
71
		switch ( $column_name ) {
72
			case 'form' :
73
				$form_title = get_the_title( $item[ $column_name ] );
74
				$form_title = empty( $form_title ) ? sprintf( __( 'Untitled (#%s)', 'give' ), $item[ $column_name ] ) : $form_title;
75
76
				return '<a href="' . esc_url( add_query_arg( 'form', $item[ $column_name ] ) ) . '" >' . $form_title . '</a>';
77
78
			case 'user_id' :
79
				if ( ! empty( $item['user_id'] ) ) {
80
					return sprintf(
81
						'<a href="%1$s">%2$s</a>',
82
						admin_url( 'edit.php?post_type=give_forms&page=give-payment-history&user=' . $item['user_id'] ),
83
						$item['donor_name']
84
					);
85
				} else {
86
					return __( 'No donor attached', 'give' );
87
				}
88
89
90
			case 'amount' :
91
				return give_currency_filter( give_format_amount( $item['amount'] ) );
92
93
			case 'status' :
94
95
				$value = '<div class="give-donation-status status-' . sanitize_title( give_get_payment_status( $payment, true ) ) . '"><span class="give-donation-status-icon"></span> ' . give_get_payment_status( $payment, true ) . '</div>';
96
97
				if ( $payment->mode == 'test' ) {
98
					$value .= Give()->tooltips->render_span( array(
99
						'label'       => __( 'This donation was made in test mode.', 'give' ),
100
						'tag_content' => __( 'Test', 'give' ),
101
						'attributes'  => array(
102
							'class' => 'give-item-label give-item-label-orange give-test-mode-transactions-label',
103
						),
104
					) );
105
				}
106
107
				return $value;
108
109
			case 'payment_id' :
110
				return '<a href="' . admin_url( 'edit.php?post_type=give_forms&page=give-payment-history&view=view-payment-details&id=' . $item['payment_id'] ) . '">' . give_get_payment_number( $item['payment_id'] ) . '</a>';
111
112
			default:
113
				return $item[ $column_name ];
114
		}
115
	}
116
117
	/**
118
	 * Retrieve the table columns
119
	 *
120
	 * @access public
121
	 * @since  1.0
122
	 * @return array $columns Array of all the list table columns
123
	 */
124
	public function get_columns() {
125
		$columns = array(
126
			'ID'         => __( 'Log ID', 'give' ),
127
			'user_id'    => __( 'Donor', 'give' ),
128
			'form'       => __( 'Form', 'give' ),
129
			'amount'     => __( 'Donation Amount', 'give' ),
130
			'status'     => __( 'Status', 'give' ),
131
			'payment_id' => __( 'Transaction ID', 'give' ),
132
			'date'       => __( 'Date', 'give' ),
133
		);
134
135
		return $columns;
136
	}
137
138
	/**
139
	 * Retrieve the current page number
140
	 *
141
	 * @access public
142
	 * @since  1.0
143
	 * @return int Current page number
144
	 */
145
	public function get_paged() {
146
		return isset( $_GET['paged'] ) ? absint( $_GET['paged'] ) : 1;
147
	}
148
149
	/**
150
	 * Retrieves the user we are filtering logs by, if any
151
	 *
152
	 * @access public
153
	 * @since  1.0
154
	 * @return mixed int If User ID, string If Email/Login
155
	 */
156
	public function get_filtered_user() {
157
		return isset( $_GET['user'] ) ? absint( $_GET['user'] ) : false;
158
	}
159
160
	/**
161
	 * Retrieves the ID of the give_form we're filtering logs by
162
	 *
163
	 * @access public
164
	 * @since  1.0
165
	 * @return int Download ID
166
	 */
167
	public function get_filtered_give_form() {
168
		return ! empty( $_GET['form'] ) ? absint( $_GET['form'] ) : false;
169
	}
170
171
	/**
172
	 * Retrieves the search query string
173
	 *
174
	 * @access public
175
	 * @since  1.0
176
	 * @return string|bool string If search is present, false otherwise
177
	 */
178
	public function get_search() {
179
		return ! empty( $_GET['s'] ) ? urldecode( trim( $_GET['s'] ) ) : false;
180
	}
181
182
183
	/**
184
	 * Display Tablenav (extended)
185
	 *
186
	 * Display the table navigation above or below the table even when no items in the logs, so nav doesn't disappear
187
	 *
188
	 * @see    : https://github.com/WordImpress/Give/issues/564
189
	 *
190
	 * @since  1.4.1
191
	 * @access protected
192
	 *
193
	 * @param string $which
194
	 */
195
	protected function display_tablenav( $which ) {
196
197
		if ( 'top' === $which ) {
198
			wp_nonce_field( 'bulk-' . $this->_args['plural'] );
199
		}
200
		?>
201
		<div class="tablenav <?php echo esc_attr( $which ); ?>">
202
203
			<div class="alignleft actions bulkactions">
204
				<?php $this->bulk_actions( $which ); ?>
205
			</div>
206
			<?php
207
			$this->extra_tablenav( $which );
208
			$this->pagination( $which );
209
			?>
210
211
			<br class="clear"/>
212
		</div>
213
		<?php
214
	}
215
216
217
	/**
218
	 * Gets the meta query for the log query
219
	 *
220
	 * This is used to return log entries that match our search query, user query, or form query
221
	 *
222
	 * @access public
223
	 * @since  1.0
224
	 * @return array $meta_query
225
	 */
226
	public function get_meta_query() {
227
		$user = $this->get_filtered_user();
228
229
		$meta_query = array();
230
231
		if ( $user ) {
232
			// Show only logs from a specific user
233
			$meta_query[] = array(
234
				'key'   => '_give_log_user_id',
235
				'value' => $user,
236
			);
237
		}
238
239
		$search = $this->get_search();
240
		if ( $search ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $search of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
241
			if ( is_email( $search ) ) {
242
				// This is an email search. We use this to ensure it works for guest users and logged-in users
243
				$key     = '_give_log_user_info';
244
				$compare = 'LIKE';
245
			} else {
246
				// Look for a user
247
				$key     = '_give_log_user_id';
248
				$compare = 'LIKE';
249
250
				if ( ! is_numeric( $search ) ) {
251
					// Searching for user by username
252
					$user = get_user_by( 'login', $search );
253
254
					if ( $user ) {
255
						// Found one, set meta value to user's ID
256
						$search = $user->ID;
257
					} else {
258
						// No user found so let's do a real search query
259
						$users = new WP_User_Query( array(
260
							'search'         => $search,
261
							'search_columns' => array( 'user_url', 'user_nicename' ),
262
							'number'         => 1,
263
							'fields'         => 'ids',
264
						) );
265
266
						$found_user = $users->get_results();
267
268
						if ( $found_user ) {
269
							$search = $found_user[0];
270
						}
271
					}
272
				}
273
			}
274
275
			if ( ! $this->file_search ) {
276
				// Meta query only works for non file name searche
277
				$meta_query[] = array(
278
					'key'     => $key,
279
					'value'   => $search,
280
					'compare' => $compare,
281
				);
282
283
			}
284
		}
285
286
		return $meta_query;
287
	}
288
289
	/**
290
	 * Outputs the log views
291
	 *
292
	 * @access public
293
	 * @since  1.0
294
	 * @return void
295
	 */
296
	function bulk_actions( $which = '' ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
297
		give_log_views();
298
	}
299
300
	/**
301
	 * Sets up the forms filter
302
	 *
303
	 * @access public
304
	 * @since  1.0
305
	 * @return void
306
	 */
307
	public function give_forms_filter() {
308
		$give_forms = get_posts( array(
309
			'post_type'              => 'give_forms',
310
			'post_status'            => 'any',
311
			'posts_per_page'         => - 1,
312
			'orderby'                => 'title',
313
			'order'                  => 'ASC',
314
			'fields'                 => 'ids',
315
			'update_post_meta_cache' => false,
316
			'update_post_term_cache' => false,
317
		) );
318
319
		if ( $give_forms ) {
320
			echo '<select name="form" id="give-log-form-filter">';
321
			echo '<option value="0">' . __( 'All', 'give' ) . '</option>';
322
			foreach ( $give_forms as $form ) {
323
				$form_title = get_the_title( $form );
324
				$form_title = empty( $form_title ) ? sprintf( __( 'Untitled (#%s)', 'give' ), $form ) : $form_title;
325
				echo '<option value="' . $form . '"' . selected( $form, $this->get_filtered_give_form() ) . '>' . esc_html( $form_title ) . '</option>';
326
			}
327
			echo '</select>';
328
		}
329
	}
330
331
	/**
332
	 * Gets the log entries for the current view
333
	 *
334
	 * @access public
335
	 * @since  1.0
336
	 *
337
	 * @return array $logs_data Array of all the Log entires
338
	 */
339
	public function get_logs() {
340
		$logs_data = array();
341
		$log_query = $this->get_query_params();
342
343
		$cache_key = Give_Cache::get_key( 'get_logs', $log_query );
344
345
		// Return result from cache if exist.
346
		if ( ! ( $logs_data = Give_Cache::get( $cache_key ) ) ) {
347
			$logs = Give()->logs->get_connected_logs( $log_query );
348
349
			if ( $logs ) {
350
				foreach ( $logs as $log ) {
351
					/* @var Give_payment $payment */
352
					$payment = new Give_Payment( $log->log_parent );
353
354
					// Make sure this payment hasn't been deleted
355
					if ( get_post( $payment->ID ) ) :
356
						$logs_data[] = array(
357
							'ID'         => '<span class="give-item-label give-item-label-gray">' . $log->ID . '</span>',
358
							'payment_id' => $payment->ID,
359
							'form'       => $payment->form_id,
360
							'amount'     => $payment->total,
361
							'user_id'    => $payment->user_id,
362
							'donor_name' => trim( "{$payment->first_name} $payment->last_name" ),
363
							'date'       => $payment->date,
364
						);
365
366
					endif;
367
				}
368
369
				// Cache results.
370
				if ( ! empty( $logs_data ) ) {
371
					Give_Cache::set( $cache_key, $logs_data );
372
				}
373
			}
374
		}
375
376
		return $logs_data;
377
	}
378
379
	/**
380
	 * Setup the final data for the table
381
	 *
382
	 * @access public
383
	 * @since  1.0
384
	 * @uses   Give_Sales_Log_Table::get_columns()
385
	 * @uses   WP_List_Table::get_sortable_columns()
386
	 * @uses   Give_Sales_Log_Table::get_pagenum()
387
	 * @uses   Give_Sales_Log_Table::get_logs()
388
	 * @uses   Give_Sales_Log_Table::get_log_count()
389
	 *
390
	 * @return void
391
	 */
392
	public function prepare_items() {
393
		$columns               = $this->get_columns();
394
		$hidden                = array();
395
		$sortable              = $this->get_sortable_columns();
396
		$this->_column_headers = array( $columns, $hidden, $sortable );
397
		$current_page          = $this->get_pagenum();
398
		$this->items           = $this->get_logs();
399
		$total_items           = Give()->logs->get_log_count( $this->get_filtered_give_form(), 'sale', $this->get_meta_query() );
400
401
		$this->set_pagination_args( array(
402
				'total_items' => $total_items,
403
				'per_page'    => $this->per_page,
404
				'total_pages' => ceil( $total_items / $this->per_page ),
405
			)
406
		);
407
	}
408
409
410
	/**
411
	 * Get log query param.
412
	 *
413
	 * @since  2.0
414
	 * @access public
415
	 *
416
	 * @return array
417
	 */
418
	public function get_query_params() {
419
		$paged     = $this->get_paged();
420
		$give_form = empty( $_GET['s'] ) ? $this->get_filtered_give_form() : null;
421
		$user      = $this->get_filtered_user();
422
423
		$log_query = array(
424
			'type'       => 'sale',
425
			'paged'      => $paged,
426
			'meta_query' => $this->get_meta_query(),
427
		);
428
429
		if ( ! empty( $give_form ) ) {
430
			$log_query['meta_query'][] = array(
431
				'key'   => '_give_log_form_id',
432
				'value' => $give_form,
433
			);
434
		}
435
436
		return $log_query;
437
	}
438
}
439