Test Failed
Push — issues/2610 ( 4e0645...7de36d )
by Ravinder
14:50
created

Give_API_Request_Log_Table::get_meta_query()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 56
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 26
nc 8
nop 0
dl 0
loc 56
rs 7.3333
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * API Requests 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
 * @since       1.0
10
 */
11
12
// Exit if accessed directly.
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
// Load WP_List_Table if not loaded
18
if ( ! class_exists( 'WP_List_Table' ) ) {
19
	require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
20
}
21
22
/**
23
 * Give_API_Request_Log_Table List Table Class
24
 *
25
 * Renders the gateway errors list table
26
 *
27
 * @since 1.0
28
 */
29
class Give_API_Request_Log_Table extends WP_List_Table {
30
	/**
31
	 * Number of items per page
32
	 *
33
	 * @var int
34
	 * @since 1.0
35
	 */
36
	public $per_page = 30;
37
38
	/**
39
	 * Get things started
40
	 *
41
	 * @since 1.0
42
	 * @see   WP_List_Table::__construct()
43
	 */
44
	public function __construct() {
45
		global $status, $page;
46
47
		// Set parent defaults
48
		parent::__construct( array(
49
			'singular' => give_get_forms_label_singular(),    // Singular name of the listed records
50
			'plural'   => give_get_forms_label_plural(),        // Plural name of the listed records
51
			'ajax'     => false,// Does this table support ajax?
52
		) );
53
	}
54
55
	/**
56
	 * Show the search field
57
	 *
58
	 * @since  1.0
59
	 * @access public
60
	 *
61
	 * @param string $text     Label for the search box
62
	 * @param string $input_id ID of the search box
63
	 *
64
	 * @return void
65
	 */
66 View Code Duplication
	public function search_box( $text, $input_id ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
67
		$input_id = $input_id . '-search-input';
68
69
		if ( ! empty( $_REQUEST['orderby'] ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
70
			echo '<input type="hidden" name="orderby" value="' . esc_attr( $_REQUEST['orderby'] ) . '" />';
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
71
		}
72
		if ( ! empty( $_REQUEST['order'] ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
73
			echo '<input type="hidden" name="order" value="' . esc_attr( $_REQUEST['order'] ) . '" />';
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
74
		}
75
		?>
76
		<p class="search-box" role="search">
77
			<label class="screen-reader-text" for="<?php echo $input_id ?>"><?php echo $text; ?>:</label>
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$input_id'
Loading history...
introduced by
Expected next thing to be a escaping function, not '$text'
Loading history...
78
			<input type="search" id="<?php echo $input_id ?>" name="s" value="<?php _admin_search_query(); ?>"/>
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$input_id'
Loading history...
79
			<?php submit_button( $text, 'button', false, false, array( 'ID' => 'search-submit' ) ); ?>
80
		</p>
81
		<?php
82
	}
83
84
	/**
85
	 * Retrieve the table columns
86
	 *
87
	 * @access public
88
	 * @since  1.0
89
	 *
90
	 * @return array $columns Array of all the list table columns
91
	 */
92
	public function get_columns() {
93
		$columns = array(
94
			'ID'      => __( 'Log ID', 'give' ),
95
			'ip'      => __( 'Request IP', 'give' ),
96
			'date'    => __( 'Date', 'give' ),
97
			'details' => __( 'Request Details', 'give' ),
98
		);
99
100
		return $columns;
101
	}
102
103
	/**
104
	 * This function renders most of the columns in the list table.
105
	 *
106
	 * @access public
107
	 * @since  1.0
108
	 *
109
	 * @param array  $item        Contains all the data of the discount code
110
	 * @param string $column_name The name of the column
111
	 *
112
	 * @return string Column Name
113
	 */
114
	public function column_default( $item, $column_name ) {
115
		switch ( $column_name ) {
116
			default:
0 ignored issues
show
Unused Code introduced by
default: return esc_attr($item[$column_name]); 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...
117
				return esc_attr( $item[ $column_name ] );
118
		}
119
	}
120
121
	/**
122
	 * Output Error Message column
123
	 *
124
	 * @access public
125
	 * @since  1.0
126
	 *
127
	 * @param array $item Contains all the data of the log
128
	 *
129
	 * @return void
130
	 */
131
	public function column_details( $item ) {
132
		echo Give()->tooltips->render_link( array(
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'Give'
Loading history...
133
			'label'       => __( 'View Request', 'give' ),
134
			'tag_content' => '<span class="dashicons dashicons-visibility"></span>',
135
			'link'        => "#TB_inline?width=640&amp;inlineId=log-details-{$item['ID']}",
136
			'attributes'  => array(
137
				'class' => 'thickbox give-error-log-details-link button button-small',
138
			),
139
		) );
140
		?>
141
		<div id="log-details-<?php echo $item['ID']; ?>" style="display:none;">
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$item'
Loading history...
142
			<?php
143
			// Print API Request.
144
			echo sprintf(
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'sprintf'
Loading history...
145
				'<p><strong>%1$s</strong></p><div>%2$s</div>',
146
				__( 'API Request:', 'give' ),
147
				Give()->logs->logmeta_db->get_meta( $item['ID'], '_give_log_api_query', true )
148
			);
149
150
			// Print Log Content, if not empty.
151
			if ( ! empty( $item['log_content'] ) ) {
152
				echo sprintf(
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'sprintf'
Loading history...
153
					'<p><strong>%1$s</strong></p><div>%2$s</div>',
154
					__( 'Error', 'give' ),
155
					esc_html( $item['log_content'] )
156
				);
157
			}
158
159
			// Print User who requested data using API.
160
			echo sprintf(
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'sprintf'
Loading history...
161
				'<p><strong>%1$s</strong></p><div>%2$s</div>',
162
				__( 'API User:', 'give' ),
163
				Give()->logs->logmeta_db->get_meta( $item['ID'], '_give_log_user', true )
164
			);
165
166
			// Print the logged key used by API.
167
			echo sprintf(
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'sprintf'
Loading history...
168
				'<p><strong>%1$s</strong></p><div>%2$s</div>',
169
				__( 'API Key:', 'give' ),
170
				Give()->logs->logmeta_db->get_meta( $item['ID'], '_give_log_key', true )
171
			);
172
173
			// Print the API Request Date.
174
			echo sprintf(
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'sprintf'
Loading history...
175
				'<p><strong>%1$s</strong></p><div>%2$s</div>',
176
				__( 'Request Date:', 'give' ),
177
				$item['log_date']
178
			);
179
			?>
180
		</div>
181
		<?php
182
	}
183
184
	/**
185
	 * Retrieves the search query string
186
	 *
187
	 * @access public
188
	 * @since  1.0
189
	 *
190
	 * @return string|bool String if search is present, false otherwise
191
	 */
192
	public function get_search() {
193
		return ! empty( $_GET['s'] ) ? urldecode( trim( $_GET['s'] ) ) : false;
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
194
	}
195
196
197
	/**
198
	 * Display Tablenav (extended)
199
	 *
200
	 * Display the table navigation above or below the table even when no items in the logs, so nav doesn't disappear
201
	 *
202
	 * @see    : https://github.com/WordImpress/Give/issues/564
203
	 *
204
	 * @since  1.4.1
205
	 * @access protected
206
	 *
207
	 * @param string $which
208
	 */
209 View Code Duplication
	protected function display_tablenav( $which ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
210
		if ( 'top' === $which ) {
211
			wp_nonce_field( 'bulk-' . $this->_args['plural'] );
212
		}
213
		?>
214
		<div class="tablenav <?php echo esc_attr( $which ); ?>">
215
216
			<div class="alignleft actions bulkactions">
217
				<?php $this->bulk_actions( $which ); ?>
218
			</div>
219
			<?php
220
			$this->extra_tablenav( $which );
221
			$this->pagination( $which );
222
			?>
223
224
			<br class="clear"/>
225
		</div>
226
		<?php
227
	}
228
229
	/**
230
	 * Gets the meta query for the log query
231
	 *
232
	 * This is used to return log entries that match our search query
233
	 *
234
	 * @access public
235
	 * @since  1.0
236
	 *
237
	 * @return array $meta_query
238
	 */
239
	function get_meta_query() {
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...
240
241
		$meta_query = array();
242
		$search     = $this->get_search();
243
244
		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...
245
			if ( filter_var( $search, FILTER_VALIDATE_IP ) ) {
246
247
				// This is an IP address search.
248
				$key = '_give_log_request_ip';
249
250
			} elseif ( is_email( $search ) ) {
251
252
				// This is an email search.
253
				$userdata = get_user_by( 'email', $search );
254
255
				if ( $userdata ) {
256
					$search = $userdata->ID;
257
				}
258
259
				$key = '_give_log_user';
260
261
			} elseif ( 32 === strlen( $search ) ) {
262
263
				// Look for an API key.
264
				$key = '_give_log_key';
265
266
			} elseif ( stristr( $search, 'token:' ) ) {
267
268
				// Look for an API token.
269
				$search = str_ireplace( 'token:', '', $search );
270
				$key    = '_give_log_token';
271
272
			} else {
273
274
				// This is (probably) a user ID search.
275
				$userdata = get_userdata( $search );
276
277
				if ( $userdata ) {
278
					$search = $userdata->ID;
279
				}
280
281
				$key = '_give_log_user';
282
283
			}
284
285
			// Setup the meta query.
286
			$meta_query[] = array(
287
				'key'     => $key,
288
				'value'   => $search,
289
				'compare' => '=',
290
			);
291
		}
292
293
		return $meta_query;
294
	}
295
296
	/**
297
	 * Retrieve the current page number
298
	 *
299
	 * @access public
300
	 * @since  1.0
301
	 *
302
	 * @return int Current page number
303
	 */
304
	public function get_paged() {
305
		return isset( $_GET['paged'] ) ? absint( $_GET['paged'] ) : 1;
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
306
	}
307
308
	/**
309
	 * Outputs the log views
310
	 *
311
	 * @param string $which Top or Bottom.
312
	 *
313
	 * @access public
314
	 * @since  1.0
315
	 *
316
	 * @return void
317
	 */
318
	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...
319
		give_log_views();
320
	}
321
322
	/**
323
	 * Gets the log entries for the current view
324
	 *
325
	 * @access public
326
	 * @since  1.0
327
	 *
328
	 * @return array $logs_data Array of all the Log entires
329
	 */
330
	public function get_logs() {
331
		$logs_data = array();
332
		$paged     = $this->get_paged();
333
		$log_query = array(
334
			'log_type'       => 'api_request',
335
			'paged'          => $paged,
336
			'meta_query'     => $this->get_meta_query(),
0 ignored issues
show
introduced by
Detected usage of meta_query, possible slow query.
Loading history...
337
			'posts_per_page' => $this->per_page,
338
		);
339
340
		$logs = Give()->logs->get_connected_logs( $log_query );
341
342
		if ( $logs ) {
343
			foreach ( $logs as $log ) {
344
345
				$logs_data[] = array(
346
					'ID'          => $log->ID,
347
					'ip'          => Give()->logs->logmeta_db->get_meta( $log->ID, '_give_log_request_ip', true ),
348
					'date'        => $log->log_date,
349
					'log_content' => $log->log_content,
350
					'log_date'    => $log->log_date,
351
				);
352
			}
353
		}
354
355
		return $logs_data;
356
	}
357
358
	/**
359
	 * Setup the final data for the table
360
	 *
361
	 * @access public
362
	 * @since  1.0
363
	 * @uses   Give_API_Request_Log_Table::get_columns()
364
	 * @uses   WP_List_Table::get_sortable_columns()
365
	 * @uses   Give_API_Request_Log_Table::get_pagenum()
366
	 * @uses   Give_API_Request_Log_Table::get_logs()
367
	 * @uses   Give_API_Request_Log_Table::get_log_count()
368
	 *
369
	 * @return void
370
	 */
371 View Code Duplication
	public function prepare_items() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
372
		$columns               = $this->get_columns();
373
		$hidden                = array(); // No hidden columns
374
		$sortable              = $this->get_sortable_columns();
375
		$this->_column_headers = array( $columns, $hidden, $sortable );
376
		$this->items           = $this->get_logs();
377
		$total_items           = Give()->logs->get_log_count( 0, 'api_request' );
378
379
		$this->set_pagination_args( array(
380
				'total_items' => $total_items,
381
				'per_page'    => $this->per_page,
382
				'total_pages' => ceil( $total_items / $this->per_page ),
383
			)
384
		);
385
	}
386
}
387