Completed
Push — master ( 3860cc...10e837 )
by Stephanie
9s
created

FrmEntriesListHelper   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 248
Duplicated Lines 1.61 %

Coupling/Cohesion

Components 2
Dependencies 7

Importance

Changes 0
Metric Value
dl 4
loc 248
rs 6.8
c 0
b 0
f 0
wmc 55
lcom 2
cbo 7

8 Methods

Rating   Name   Duplication   Size   Complexity  
F prepare_items() 0 41 11
A no_items() 0 17 4
A search_box() 0 3 1
A extra_tablenav() 0 9 3
A get_primary_column_name() 0 15 4
F single_row() 0 94 24
A get_actions() 4 10 2
B get_column_value() 0 36 6

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like FrmEntriesListHelper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FrmEntriesListHelper, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
class FrmEntriesListHelper extends FrmListHelper {
4
	protected $column_name;
5
	protected $item;
6
	protected $field;
7
8
	public function prepare_items() {
9
        global $per_page;
10
11
		$per_page = $this->get_items_per_page( 'formidable_page_formidable_entries_per_page' );
0 ignored issues
show
introduced by
Overridding WordPress globals is prohibited
Loading history...
12
        $form_id = $this->params['form'];
13
14
		$default_orderby = 'id';
15
		$default_order = 'DESC';
16
		$s_query = array();
17
18
		if ( $form_id ) {
19
			$s_query['it.form_id'] = $form_id;
20
		}
21
22
		$s = isset( $_REQUEST['s'] ) ? stripslashes($_REQUEST['s']) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
23
24
	    if ( $s != '' && FrmAppHelper::pro_is_installed() ) {
25
	        $fid = isset( $_REQUEST['fid'] ) ? sanitize_title( $_REQUEST['fid'] ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
26
	        $s_query = FrmProEntriesHelper::get_search_str( $s_query, $s, $form_id, $fid );
27
	    }
28
29
        $orderby = isset( $_REQUEST['orderby'] ) ? sanitize_title( $_REQUEST['orderby'] ) : $default_orderby;
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
30
        if ( strpos($orderby, 'meta') !== false ) {
31
            $order_field_type = FrmField::get_type( str_replace( 'meta_', '', $orderby ) );
32
			$orderby .= in_array( $order_field_type, array( 'number', 'scale' ) ) ? ' +0 ' : '';
33
        }
34
35
		$order = isset( $_REQUEST['order'] ) ? sanitize_title( $_REQUEST['order'] ) : $default_order;
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
36
		$order = ' ORDER BY ' . $orderby . ' ' . $order;
37
38
        $page = $this->get_pagenum();
39
		$start = (int) isset( $_REQUEST['start'] ) ? absint( $_REQUEST['start'] ) : ( ( $page - 1 ) * $per_page );
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
40
41
		$this->items = FrmEntry::getAll( $s_query, $order, ' LIMIT ' . $start . ',' . $per_page, true, false );
42
        $total_items = FrmEntry::getRecordCount($s_query);
43
44
		$this->set_pagination_args( array(
45
			'total_items' => $total_items,
46
			'per_page' => $per_page,
47
		) );
48
	}
49
50
	public function no_items() {
51
        $s = isset( $_REQUEST['s'] ) ? $_REQUEST['s'] : '';
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
52
	    if ( ! empty($s) ) {
53
            _e( 'No Entries Found', 'formidable' );
54
            return;
55
        }
56
57
		$form_id = $this->params['form'];
58
		$form = $this->params['form'];
59
60
        if ( $form_id ) {
61
            $form = FrmForm::getOne($form_id);
62
        }
63
        $colspan = $this->get_column_count();
64
65
		include( FrmAppHelper::plugin_path() . '/classes/views/frm-entries/no_entries.php' );
66
	}
67
68
	public function search_box( $text, $input_id ) {
69
		// Searching is a pro feature
70
	}
71
72
	protected function extra_tablenav( $which ) {
73
		$form_id = FrmAppHelper::simple_get( 'form', 'absint' );
74
		if ( $which == 'top' && empty( $form_id ) ) {
75
			echo '<div class="alignleft actions">';
76
			echo FrmFormsHelper::forms_dropdown( 'form', $form_id, array( 'blank' => __( 'View all forms', 'formidable' ) ) );
1 ignored issue
show
Bug introduced by
It seems like $form_id defined by \FrmAppHelper::simple_get('form', 'absint') on line 73 can also be of type array; however, FrmFormsHelper::forms_dropdown() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw 'FrmFormsHelper'
Loading history...
77
			submit_button( __( 'Filter' ), 'filter_action', '', false, array( 'id' => "post-query-submit" ) );
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal post-query-submit does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
78
			echo '</div>';
79
		}
80
	}
81
82
	/**
83
	* Gets the name of the primary column in the Entries screen
84
	*
85
	* @since 2.0.14
86
	*
87
	* @return string $primary_column
88
	*/
89
	protected function get_primary_column_name() {
90
		$columns = get_column_headers( $this->screen );
91
		$hidden = get_hidden_columns( $this->screen );
92
93
		$primary_column = '';
94
95
		foreach ( $columns as $column_key => $column_display_name ) {
96
			if ( 'cb' != $column_key && ! in_array( $column_key, $hidden ) ) {
97
				$primary_column = $column_key;
98
				break;
99
			}
100
		}
101
102
		return $primary_column;
103
	}
104
105
	public function single_row( $item, $style = '' ) {
106
		// Set up the hover actions for this user
107
		$actions = array();
108
		$view_link = '?page=formidable-entries&frm_action=show&id=' . $item->id;
109
110
		$this->get_actions( $actions, $item, $view_link );
111
112
        $action_links = $this->row_actions( $actions );
113
114
		// Set up the checkbox ( because the user is editable, otherwise its empty )
115
		$checkbox = "<input type='checkbox' name='item-action[]' id='cb-item-action-{$item->id}' value='{$item->id}' />";
116
117
		$r = "<tr id='item-action-{$item->id}'$style>";
118
119
		list( $columns, $hidden, , $primary ) = $this->get_column_info();
120
        $action_col = false;
121
122
		foreach ( $columns as $column_name => $column_display_name ) {
123
			$class = $column_name . ' column-' . $column_name;
124
125
			if ( $column_name === $primary ) {
126
				$class .= ' column-primary';
127
			}
128
129
			if ( in_array( $column_name, $hidden ) ) {
130
				$class .= ' frm_hidden';
131
			} else if ( ! $action_col && ! in_array( $column_name, array( 'cb', 'id', 'form_id', 'post_id' ) ) ) {
132
			    $action_col = $column_name;
133
            }
134
135
			$attributes = 'class="' . esc_attr( $class ) . '"';
136
			unset($class);
137
			$attributes .= ' data-colname="' . $column_display_name . '"';
138
139
			$form_id = $this->params['form'] ? $this->params['form'] : 0;
140
			$col_name = preg_replace( '/^(' . $form_id . '_)/', '', $column_name );
141
			$this->column_name = $col_name;
142
143
			switch ( $col_name ) {
144
				case 'cb':
145
					$r .= "<th scope='row' class='check-column'>$checkbox</th>";
146
					break;
147
				case 'ip':
148
				case 'id':
149
				case 'item_key':
150
				    $val = $item->{$col_name};
151
				    break;
152
				case 'name':
153
				case 'description':
154
				    $val = FrmAppHelper::truncate(strip_tags($item->{$col_name}), 100);
155
				    break;
156
				case 'created_at':
157
				case 'updated_at':
158
				    $date = FrmAppHelper::get_formatted_time($item->{$col_name});
159
					$val = '<abbr title="' . esc_attr( FrmAppHelper::get_formatted_time( $item->{$col_name}, '', 'g:i:s A' ) ) . '">' . $date . '</abbr>';
160
					break;
161
				case 'is_draft':
162
				    $val = empty($item->is_draft) ? __( 'No') : __( 'Yes');
163
			        break;
164
				case 'form_id':
165
				    $val = FrmFormsHelper::edit_form_link($item->form_id);
166
    				break;
167
				case 'post_id':
168
				    $val = FrmAppHelper::post_edit_link($item->post_id);
169
				    break;
170
				case 'user_id':
171
				    $user = get_userdata($item->user_id);
172
				    $val = $user->user_login;
173
				    break;
174
				default:
175
					$val = apply_filters( 'frm_entries_' . $col_name . '_column', false, compact( 'item' ) );
176
					if ( $val === false ) {
177
						$this->get_column_value( $item, $val );
178
					}
179
				break;
180
			}
181
182
			if ( isset( $val ) ) {
183
			    $r .= "<td $attributes>";
184
				if ( $column_name == $action_col ) {
185
					$edit_link = '?page=formidable-entries&frm_action=edit&id=' . $item->id;
186
					$r .= '<a href="' . esc_url( isset( $actions['edit'] ) ? $edit_link : $view_link ) . '" class="row-title" >' . $val . '</a> ';
187
			        $r .= $action_links;
188
				} else {
189
			        $r .= $val;
190
			    }
191
			    $r .= '</td>';
192
			}
193
			unset($val);
194
		}
195
		$r .= '</tr>';
196
197
		return $r;
198
	}
199
200
    /**
201
     * @param string $view_link
202
     */
203
    private function get_actions( &$actions, $item, $view_link ) {
204
		$actions['view'] = '<a href="' . esc_url( $view_link ) . '">' . __( 'View', 'formidable' ) . '</a>';
205
206 View Code Duplication
        if ( current_user_can('frm_delete_entries') ) {
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...
207
			$delete_link = '?page=formidable-entries&frm_action=destroy&id=' . $item->id . '&form=' . $this->params['form'];
208
			$actions['delete'] = '<a href="' . esc_url( wp_nonce_url( $delete_link ) ) . '" class="submitdelete" onclick="return confirm(\'' . esc_attr( __( 'Are you sure you want to delete that?', 'formidable' ) ) . '\')">' . __( 'Delete' ) . '</a>';
0 ignored issues
show
introduced by
Expected a sanitizing function (see Codex for 'Data Validation'), but instead saw '__'
Loading history...
209
	    }
210
211
        $actions = apply_filters('frm_row_actions', $actions, $item);
212
    }
213
214
	private function get_column_value( $item, &$val ) {
215
		$col_name = $this->column_name;
216
217
		if ( strpos( $col_name, 'frmsep_' ) === 0 ) {
218
			$sep_val = true;
219
			$col_name = str_replace( 'frmsep_', '', $col_name );
220
		} else {
221
			$sep_val = false;
222
		}
223
224
		if ( strpos( $col_name, '-_-' ) ) {
225
			list( $col_name, $embedded_field_id ) = explode( '-_-', $col_name );
226
		}
227
228
		$field = FrmField::getOne( $col_name );
229
		if ( ! $field ) {
230
			return;
231
		}
232
233
		$atts = array(
234
			'type' => $field->type, 'truncate' => true,
235
			'post_id' => $item->post_id, 'entry_id' => $item->id,
236
			'embedded_field_id' => 0,
237
		);
238
239
		if ( $sep_val ) {
240
			$atts['saved_value'] = true;
241
		}
242
243
		if ( isset( $embedded_field_id ) ) {
244
			$atts['embedded_field_id'] = $embedded_field_id;
245
			unset( $embedded_field_id );
246
		}
247
248
		$val = FrmEntriesHelper::prepare_display_value( $item, $field, $atts );
249
	}
250
}
251