Completed
Push — develop ( 86f86c...e68333 )
by Zack
30:59
created

render_field_options()   B

Complexity

Conditions 9
Paths 60

Size

Total Lines 66

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 10.2655

Importance

Changes 0
Metric Value
cc 9
nc 60
nop 11
dl 0
loc 66
ccs 21
cts 28
cp 0.75
crap 10.2655
rs 7.1862
c 0
b 0
f 0

How to fix   Long Method    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/**
3
 * Renders field/widget options and view settings
4
 *
5
 * @package   GravityView
6
 * @license   GPL2+
7
 * @author    Katz Web Services, Inc.
8
 * @link      http://gravityview.co
9
 * @copyright Copyright 2014, Katz Web Services, Inc.
10
 *
11
 * @since 1.2
12
 */
13
14
class GravityView_Render_Settings {
15
16
	/**
17
	 * Get the default options for a standard field.
18
	 *
19
	 * @param  string      $field_type  Type of field options to render (`field` or `widget`)
20
	 * @param  string      $template_id Table slug
21
	 * @param  float       $field_id    GF Field ID - Example: `3`, `5.2`, `entry_link`, `created_by`
22
	 * @param  string      $context     What context are we in? Example: `single` or `directory`
23
	 * @param  string      $input_type  (textarea, list, select, etc.)
24
	 * @param  int         $form_id     The form ID. @since develop
25
	 * @return array       Array of field options with `label`, `value`, `type`, `default` keys
26
	 */
27 2
	public static function get_default_field_options( $field_type, $template_id, $field_id, $context, $input_type, $form_id ) {
28
29 2
		$field_options = array();
30
31 2
		if( 'field' === $field_type ) {
32
33
			// Default options - fields
34
			$field_options = array(
35 2
				'show_label' => array(
36 2
					'type' => 'checkbox',
37 2
					'label' => __( 'Show Label', 'gravityview' ),
38
					'value' => true,
39
				),
40
				'custom_label' => array(
41 2
					'type' => 'text',
42 2
					'label' => __( 'Custom Label:', 'gravityview' ),
43 2
					'value' => '',
44 2
					'class'      => 'widefat',
45
					'merge_tags' => true,
46
				),
47
				'custom_class' => array(
48 2
					'type' => 'text',
49 2
					'label' => __( 'Custom CSS Class:', 'gravityview' ),
50 2
					'desc' => __( 'This class will be added to the field container', 'gravityview'),
51 2
					'value' => '',
52
					'merge_tags' => true,
53 2
					'tooltip' => 'gv_css_merge_tags',
54 2
					'class'      => 'widefat code',
55
				),
56
				'only_loggedin' => array(
57 2
					'type' => 'checkbox',
58 2
					'label' => __( 'Make visible only to logged-in users?', 'gravityview' ),
59 2
					'value' => ''
60
				),
61
				'only_loggedin_cap' => array(
62 2
					'type' => 'select',
63 2
					'label' => __( 'Make visible for:', 'gravityview' ),
64 2
					'options' => self::get_cap_choices( $template_id, $field_id, $context, $input_type ),
65 2
					'class' => 'widefat',
66 2
					'value' => 'read',
67
				),
68
			);
69
70
			// Match Table as well as DataTables
71 2
			if( preg_match( '/table/ism', $template_id ) && 'directory' === $context ) {
72 1
				$field_options['width'] = array(
73 1
					'type' => 'number',
74 1
					'label' => __('Percent Width', 'gravityview'),
75 1
					'desc' => __( 'Leave blank for column width to be based on the field content.', 'gravityview'),
76 1
					'class' => 'code widefat',
77 1
					'value' => '',
78
				);
79
			}
80
81
		}
82
83
		/**
84
		 * @filter `gravityview_template_{$field_type}_options` Filter the field options by field type. Filter names: `gravityview_template_field_options` and `gravityview_template_widget_options`
85
		 * @param[in,out] array    Array of field options with `label`, `value`, `type`, `default` keys
86
		 * @param[in]  string      $template_id Table slug
87
		 * @param[in]  float       $field_id    GF Field ID - Example: `3`, `5.2`, `entry_link`, `created_by`
88
		 * @param[in]  string      $context     What context are we in? Example: `single` or `directory`
89
		 * @param[in]  string      $input_type  (textarea, list, select, etc.)
90
		 * @param[in]  int         $form_id     The form ID. @since develop
91
		 */
92 2
		$field_options = apply_filters( "gravityview_template_{$field_type}_options", $field_options, $template_id, $field_id, $context, $input_type, $form_id );
93
94
		/**
95
		 * @filter `gravityview_template_{$input_type}_options` Filter the field options by input type (`$input_type` examples: `textarea`, `list`, `select`, etc.)
96
		 * @param[in,out] array    Array of field options with `label`, `value`, `type`, `default` keys
97
		 * @param[in]  string      $template_id Table slug
98
		 * @param[in]  float       $field_id    GF Field ID - Example: `3`, `5.2`, `entry_link`, `created_by`
99
		 * @param[in]  string      $context     What context are we in? Example: `single` or `directory`
100
		 * @param[in]  string      $input_type  (textarea, list, select, etc.)
101
		 * @param[in]  int         $form_id     The form ID. @since develop
102
		 */
103 2
		$field_options = apply_filters( "gravityview_template_{$input_type}_options", $field_options, $template_id, $field_id, $context, $input_type, $form_id );
104
105 2
		return $field_options;
106
	}
107
108
	/**
109
	 * Get capabilities options for GravityView
110
	 *
111
	 * Parameters are only to pass to the filter.
112
	 *
113
	 * @param  string $template_id Optional. View slug
114
	 * @param  string $field_id    Optional. GF Field ID - Example: `3`, `5.2`, `entry_link`, `created_by`
115
	 * @param  string $context     Optional. What context are we in? Example: `single` or `directory`
116
	 * @param  string $input_type  Optional. (textarea, list, select, etc.)
117
	 * @return array Associative array, with the key being the capability and the value being the label shown.
118
	 */
119 1
	static public function get_cap_choices( $template_id = '', $field_id = '', $context = '', $input_type = '' ) {
120
121
		$select_cap_choices = array(
122 1
			'read' => __( 'Any Logged-In User', 'gravityview' ),
123 1
			'publish_posts' => __( 'Author Or Higher', 'gravityview' ),
124 1
			'gravityforms_view_entries' => __( 'Can View Gravity Forms Entries', 'gravityview' ),
125 1
			'delete_others_posts' => __( 'Editor Or Higher', 'gravityview' ),
126 1
			'gravityforms_edit_entries' => __( 'Can Edit Gravity Forms Entries', 'gravityview' ),
127 1
			'manage_options' => __( 'Administrator', 'gravityview' ),
128
		);
129
130 1
		if( is_multisite() ) {
131
			$select_cap_choices['manage_network'] = __('Multisite Super Admin', 'gravityview' );
132
		}
133
134
		/**
135
		 * @filter `gravityview_field_visibility_caps` Modify the capabilities shown in the field dropdown
136
		 * @see https://docs.gravityview.co/article/96-how-to-modify-capabilities-shown-in-the-field-only-visible-to-dropdown
137
		 * @since  1.0.1
138
		 * @param  array $select_cap_choices Associative rray of role slugs with labels ( `manage_options` => `Administrator` )
139
		 * @param  string $template_id Optional. View slug
140
		 * @param  string $field_id    Optional. GF Field ID - Example: `3`, `5.2`, `entry_link`, `created_by`
141
		 * @param  string $context     Optional. What context are we in? Example: `single` or `directory`
142
		 * @param  string $input_type  Optional. (textarea, list, select, etc.)
143
		 */
144 1
		$select_cap_choices = apply_filters('gravityview_field_visibility_caps', $select_cap_choices, $template_id, $field_id, $context, $input_type );
145
146 1
		return $select_cap_choices;
147
	}
148
149
150
	/**
151
	 * Render Field Options html (shown through a dialog box)
152
	 *
153
	 * @see GravityView_Ajax::get_field_options
154
	 * @see GravityView_Admin_Views::render_active_areas
155
	 *
156
	 * @access public
157
	 * @param string $form_id
158
	 * @param string $field_type field / widget
159
	 * @param string $template_id
160
	 * @param string $field_id
161
	 * @param string $field_label
162
	 * @param string $area
163
	 * @param string $uniqid (default: '')
164
	 * @param string $current (default: '')
165
	 * @param string $context (default: 'single')
166
	 * @param array $item Field or widget array that's being rendered
167
	 *
168
	 * @return string HTML of dialog box
169
	 */
170 1
	public static function render_field_options( $form_id, $field_type, $template_id, $field_id, $field_label, $area, $input_type = NULL, $uniqid = '', $current = '', $context = 'single', $item = array() ) {
171
172 1
		if( empty( $uniqid ) ) {
173
			//generate a unique field id
174
			$uniqid = uniqid('', false);
175
		}
176
177
		// get field/widget options
178 1
		$options = self::get_default_field_options( $field_type, $template_id, $field_id, $context, $input_type, $form_id );
179
180
		// two different post arrays, depending of the field type
181 1
		$name_prefix = $field_type .'s' .'['. $area .']['. $uniqid .']';
182
183
		// build output
184 1
		$output = '';
185 1
		$output .= '<input type="hidden" class="field-key" name="'. $name_prefix .'[id]" value="'. esc_attr( $field_id ) .'">';
186 1
		$output .= '<input type="hidden" class="field-label" name="'. $name_prefix .'[label]" value="'. esc_attr( $field_label ) .'">';
187 1
		if ( $form_id ) {
188 1
			$output .= '<input type="hidden" class="field-form-id" name="'. $name_prefix .'[form_id]" value="'. esc_attr( $form_id ) .'">';
189
		}
190
191
		// If there are no options, return what we got.
192 1
		if(empty($options)) {
193
194
			// This is here for checking if the output is empty in render_label()
195
			$output .= '<!-- No Options -->';
196
197
			return $output;
198
		}
199
200 1
		$output .= '<div class="gv-dialog-options" title="'. esc_attr( sprintf( __( 'Options: %s', 'gravityview' ) , strip_tags( html_entity_decode( $field_label ) ) ) ) .'">';
201
202
		/**
203
		 * @since 1.8
204
		 */
205 1
		if( !empty( $item['subtitle'] ) ) {
206
			$output .= '<div class="subtitle">' . $item['subtitle'] . '</div>';
207
		}
208
209 1
		foreach( $options as $key => $option ) {
210
211 1
			$value = isset( $current[ $key ] ) ? $current[ $key ] : NULL;
212
213 1
			$field_output = self::render_field_option( $name_prefix . '['. $key .']' , $option, $value);
214
215
			// The setting is empty
216 1
			if( empty( $field_output ) ) {
217
				continue;
218
			}
219
220 1
			switch( $option['type'] ) {
221
				// Hide hidden fields
222 1
				case 'hidden':
223
					$output .= '<div class="gv-setting-container gv-setting-container-'. esc_attr( $key ) . ' screen-reader-text">'. $field_output . '</div>';
224
					break;
225
				default:
226 1
					$output .= '<div class="gv-setting-container gv-setting-container-'. esc_attr( $key ) . '">'. $field_output .'</div>';
227
			}
228
		}
229
230
		// close options window
231 1
		$output .= '</div>';
232
233 1
		return $output;
234
235
	}
236
237
238
239
	/**
240
	 * Handle rendering a field option form element
241
	 *
242
	 * @param  string     $name    Input `name` attribute
243
	 * @param  array      $option  Associative array of options. See the $defaults variable for available keys.
244
	 * @param  mixed      $curr_value Current value of option
245
	 * @return string     HTML output of option
246
	 */
247
	public static function render_field_option( $name = '', $option, $curr_value = NULL ) {
248
249
		$output = '';
250
251
		/**
252
		 * @deprecated setting index 'default' was replaced by 'value'
253
		 * @see GravityView_FieldType::get_field_defaults
254
		 */
255
		if( !empty( $option['default'] ) && empty( $option['value'] ) ) {
256
			$option['value'] = $option['default'];
257
			_deprecated_function( 'GravityView_FieldType::get_field_defaults', '1.1.7', '[value] instead of [default] when defining the setting '. $name .' details' );
258
		}
259
260
		// prepare to render option field type
261
		if( isset( $option['type'] ) ) {
262
263
			$type_class = self::load_type_class( $option );
264
265
			if( class_exists( $type_class ) ) {
266
267
				/** @var GravityView_FieldType $render_type */
268
				$render_type = new $type_class( $name, $option, $curr_value );
269
270
				ob_start();
271
272
				$render_type->render_option();
273
274
				$output = ob_get_clean();
275
276
				/**
277
				 * @filter `gravityview/option/output/{option_type}` Modify the output for a GravityView setting.\n
278
				 * `$option_type` is the type of setting (`radio`, `text`, etc.)
279
				 * @param[in,out] string $output field class name
280
				 * @param[in] array $option  option field data
281
				 */
282
				$output = apply_filters( "gravityview/option/output/{$option['type']}" , $output, $option );
283
			}
284
285
		} // isset option[type]
286
287
		return $output;
288
	}
289
290
291
292
293
294
295
	/**
296
	 * Output a table row for view settings
297
	 * @param  string $key              The key of the input
298
	 * @param  array  $current_settings Associative array of current settings to use as input values, if set. If not set, the defaults are used.
299
	 * @param  string $override_input   [description]
300
	 * @param  string $name             [description]
301
	 * @param  string $id               [description]
302
	 * @return void                   [description]
303
	 */
304
	public static function render_setting_row( $key = '', $current_settings = array(), $override_input = null, $name = 'template_settings[%s]', $id = 'gravityview_se_%s' ) {
305
306
		$settings = \GV\View_Settings::with_defaults( true );
307
308
		// If the key doesn't exist, there's something wrong.
309
		if ( ! $setting = $settings->get( $key ) ) {
310
			return;
311
		}
312
313
		/**
314
		 * @deprecated setting index 'name' was replaced by 'label'
315
		 * @see GravityView_FieldType::get_field_defaults
316
		 */
317
		if( isset( $setting['name'] ) && empty( $setting['label'] ) ) {
318
			$setting['label'] = $setting['name'];
319
			_deprecated_function( 'GravityView_FieldType::get_field_defaults', '1.1.7', '[label] instead of [name] when defining the setting '. $key .' details' );
320
		}
321
322
		$name = esc_attr( sprintf( $name, $key ) );
323
		$setting['id'] = esc_attr( sprintf( $id, $key ) );
324
		$setting['tooltip'] = 'gv_' . $key;
325
326
		// Use default if current setting isn't set.
327
		$curr_value = isset( $current_settings[ $key ] ) ? $current_settings[ $key ] : $setting['value'];
328
329
		// default setting type = text
330
		$setting['type'] = empty( $setting['type'] ) ? 'text' : $setting['type'];
331
332
		// merge tags
333
		if( !isset( $setting['merge_tags'] ) ) {
334
			if( $setting['type'] === 'text' ) {
335
				$setting['merge_tags'] = true;
336
			} else {
337
				$setting['merge_tags'] = false;
338
			}
339
		}
340
341
		$output = '';
342
343
		// render the setting
344
		$type_class = self::load_type_class( $setting );
345
		if( class_exists( $type_class ) ) {
346
			/** @var GravityView_FieldType $render_type */
347
			$render_type = new $type_class( $name, $setting, $curr_value );
348
			ob_start();
349
			$render_type->render_setting( $override_input );
350
			$output = ob_get_clean();
351
		}
352
353
		// Check if setting is specific for a template
354
		if( !empty( $setting['show_in_template'] ) ) {
355
			if( !is_array( $setting['show_in_template'] ) ) {
356
				$setting['show_in_template'] = array( $setting['show_in_template'] );
357
			}
358
			$show_if = ' data-show-if="'. implode( ' ', $setting['show_in_template'] ).'"';
359
		} else {
360
			$show_if = '';
361
		}
362
363
		if( ! empty( $setting['requires'] ) ) {
364
			$show_if .= sprintf( ' data-requires="%s"', $setting['requires'] );
365
		}
366
367
		if( ! empty( $setting['requires_not'] ) ) {
368
			$show_if .= sprintf( ' data-requires-not="%s"', $setting['requires_not'] );
369
		}
370
371
		// output
372
		echo '<tr valign="top" '. $show_if .'>' . $output . '</tr>';
373
374
	}
375
376
377
	/**
378
	 * Given a field type calculates the php class. If not found try to load it.
379
	 * @param  array $field
380
	 * @return string type class name
381
	 */
382
	public static function load_type_class( $field = NULL ) {
383
384
		if( empty( $field['type'] ) ) {
385
			return NULL;
386
		}
387
388
		/**
389
		 * @filter `gravityview/setting/class/{field_type}`
390
		 * @param string $class_suffix  field class suffix; `GravityView_FieldType_{$class_suffix}`
391
		 * @param array $field   field data
392
		 */
393
		$type_class = apply_filters( "gravityview/setting/class/{$field['type']}", 'GravityView_FieldType_' . $field['type'], $field );
394
395
		if( !class_exists( $type_class ) ) {
396
397
			/**
398
			 * @filter `gravityview/setting/class_file/{field_type}`
399
			 * @param string  $field_type_include_path field class file path
400
			 * @param array $field  field data
401
			 */
402
			$class_file = apply_filters( "gravityview/setting/class_file/{$field['type']}", GRAVITYVIEW_DIR . "includes/admin/field-types/type_{$field['type']}.php", $field );
403
404
			if( $class_file ) {
405
				if( file_exists( $class_file ) ) {
406
					require_once( $class_file );
407
				}
408
			}
409
410
		}
411
412
		return $type_class;
413
	}
414
415
416
417
418
419
	/**
420
	 * @deprecated 1.2
421
	 * Render the HTML for a checkbox input to be used on the field & widgets options
422
	 * @param  string $name , name attribute
423
	 * @param  string $current current value
424
	 * @return string         html tags
425
	 */
426
	public static function render_checkbox_option( $name = '', $id = '', $current = '' ) {
427
428
		_deprecated_function( __METHOD__, '1.2', 'GravityView_FieldType_checkbox::render_input' );
429
430
		$output  = '<input name="'. esc_attr( $name ) .'" type="hidden" value="0">';
431
		$output .= '<input name="'. esc_attr( $name ) .'" id="'. esc_attr( $id ) .'" type="checkbox" value="1" '. checked( $current, '1', false ) .' >';
432
433
		return $output;
434
	}
435
436
437
	/**
438
	 * @deprecated 1.2
439
	 * Render the HTML for an input text to be used on the field & widgets options
440
	 * @param  string $name    Unique name of the field. Exampe: `fields[directory_list-title][5374ff6ab128b][custom_label]`
441
	 * @param  string $current [current value]
442
	 * @param string $add_merge_tags Add merge tags to the input?
443
	 * @param array $args Field settings, including `class` key for CSS class
444
	 * @return string         [html tags]
445
	 */
446
	public static function render_text_option( $name = '', $id = '', $current = '', $add_merge_tags = NULL, $args = array() ) {
447
448
		_deprecated_function( __METHOD__, '1.2', 'GravityView_FieldType_text::render_input' );
449
450
		// Show the merge tags if the field is a list view
451
		$is_list = ( preg_match( '/_list-/ism', $name ));
452
453
		// Or is a single entry view
454
		$is_single = ( preg_match( '/single_/ism', $name ));
455
		$show = ( $is_single || $is_list );
456
457
		$class = '';
458
		// and $add_merge_tags is not false
459
		if( $show && $add_merge_tags !== false || $add_merge_tags === 'force' ) {
460
			$class = 'merge-tag-support mt-position-right mt-hide_all_fields ';
461
		}
462
463
		$class .= !empty( $args['class'] ) ? $args['class'] : 'widefat';
464
		$type = !empty( $args['type'] ) ? $args['type'] : 'text';
465
466
		return '<input name="'. esc_attr( $name ) .'" id="'. esc_attr( $id ) .'" type="'.esc_attr($type).'" value="'. esc_attr( $current ) .'" class="'.esc_attr( $class ).'">';
467
	}
468
469
	/**
470
	 * @deprecated 1.2
471
	 * Render the HTML for an textarea input to be used on the field & widgets options
472
	 * @param  string $name    Unique name of the field. Exampe: `fields[directory_list-title][5374ff6ab128b][custom_label]`
473
	 * @param  string $current [current value]
474
	 * @param string|boolean $add_merge_tags Add merge tags to the input?
475
	 * @param array $args Field settings, including `class` key for CSS class
476
	 * @return string         [html tags]
477
	 */
478
	public static function render_textarea_option( $name = '', $id = '', $current = '', $add_merge_tags = NULL, $args = array() ) {
479
480
		_deprecated_function( __METHOD__, '1.2', 'GravityView_FieldType_textarea::render_input' );
481
482
		// Show the merge tags if the field is a list view
483
		$is_list = ( preg_match( '/_list-/ism', $name ));
484
485
		// Or is a single entry view
486
		$is_single = ( preg_match( '/single_/ism', $name ));
487
		$show = ( $is_single || $is_list );
488
489
		$class = '';
490
		// and $add_merge_tags is not false
491
		if( $show && $add_merge_tags !== false || $add_merge_tags === 'force' ) {
492
			$class = 'merge-tag-support mt-position-right mt-hide_all_fields ';
493
		}
494
495
		$class .= !empty( $args['class'] ) ? 'widefat '.$args['class'] : 'widefat';
496
497
		return '<textarea name="'. esc_attr( $name ) .'" id="'. esc_attr( $id ) .'" class="'.esc_attr( $class ).'">'. esc_textarea( $current ) .'</textarea>';
498
	}
499
500
	/**
501
	 *
502
	 * Render the HTML for a select box to be used on the field & widgets options
503
	 * @deprecated 1.2
504
	 * @param  string $name    [name attribute]
505
	 * @param  array $choices [select options]
506
	 * @param  string $current [current value]
507
	 * @return string          [html tags]
508
	 */
509
	public static function render_select_option( $name = '', $id = '', $choices, $current = '' ) {
510
511
		_deprecated_function( __METHOD__, '1.2', 'GravityView_FieldType_select::render_input' );
512
513
		$output = '<select name="'. $name .'" id="'. $id .'">';
514
		foreach( $choices as $value => $label ) {
515
			$output .= '<option value="'. esc_attr( $value ) .'" '. selected( $value, $current, false ) .'>'. esc_html( $label ) .'</option>';
516
		}
517
		$output .= '</select>';
518
519
		return $output;
520
	}
521
522
523
}
524