Passed
Push — master ( 57a609...ec0975 )
by Chris
04:27
created

MAG_CMB2_Field_Post_Search_Ajax::render()   D

Complexity

Conditions 18
Paths 19

Size

Total Lines 84
Code Lines 62

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 18
eloc 62
c 4
b 0
f 0
nc 19
nop 5
dl 0
loc 84
rs 4.8666

How to fix   Long Method    Complexity   

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
 * Class MAG_CMB2_Field_Post_Search_Ajax
4
 */
5
6
if ( ! class_exists( 'MAG_CMB2_Field_Post_Search_Ajax' ) ) {
7
8
	/**
9
	 * The LSX Post Search Field
10
	 */
11
	class MAG_CMB2_Field_Post_Search_Ajax {
12
13
		/**
14
		 * Current version number
15
		 */
16
		const VERSION = '1.0.0';
17
18
		/**
19
		 * The url which is used to load local resources
20
		 * 
21
		 * @var string
22
		 */
23
		protected static $url = '';
24
25
		/**
26
		 * Initialize the plugin by hooking into CMB2
27
		 */
28
		public function __construct() {
29
			add_action( 'cmb2_render_post_search_ajax', array( $this, 'render' ), 10, 5 );
30
			add_action( 'cmb2_sanitize_post_search_ajax', array( $this, 'sanitize' ), 10, 4 );
31
			add_action( 'wp_ajax_cmb_post_search_ajax_get_results', array( $this, 'cmb_post_search_ajax_get_results' ) );
32
		}
33
34
		/**
35
		 * Render field
36
		 */
37
		public function render( $field, $value, $object_id, $object_type, $field_type ) {	
38
			$this->setup_admin_scripts();
39
			$field_name = $field->_name();
40
41
			if ( $field->args( 'limit' ) > 1 ) {
42
43
				echo '<ul class="cmb-post-search-ajax-results" id="' . $field_name . '_results">';
44
				if ( isset( $value ) && ! empty( $value ) ) {
45
					if ( ! is_array( $value ) ) {
46
						$value = array( $value );
47
					}
48
					$value = array_unique( $value );
49
					foreach ( $value as $val ) {
50
						$handle = ( $field->args( 'sortable' ) ) ? '<span class="hndl"></span>' : '';
51
						$li_css = '';
52
						if ( $field->args( 'object_type' ) == 'user' ) {
53
							$guid  = get_edit_user_link( $val );
54
							$user  = get_userdata( $val );
55
							$title = $user->display_name;
56
						} else {
57
							$guid  = get_edit_post_link( $val );
58
							$title = get_the_title( $val );
59
							if ( 'trash' === get_post_status( $val ) ) {
60
								$li_css = 'display:none;';
61
							}
62
						}
63
						echo '<li style="' . $li_css . '">' . $handle . '<input type="hidden" name="' . $field_name . '_results[]" value="' . $val . '"><a href="' . $guid . '" target="_blank" class="edit-link">' . $title . '</a><a class="remover"><span class="dashicons dashicons-no"></span><span class="dashicons dashicons-dismiss"></span></a></li>';
64
					}
65
				}
66
				echo '</ul>';
67
				$field_value = '';
68
			} else {
69
				if ( is_array( $value ) ) {
70
					$value = $value[0];
71
				}
72
				if ( $field->args( 'object_type' ) == 'user' ) {
73
					$field_value = ( $value ? get_userdata( $value )->display_name : '' );
74
				} else {
75
					$field_value = ( $value ? get_the_title( $value ) : '' );
76
				}
77
				echo $field_type->input( 
78
					array(
79
						'type'  => 'hidden',
80
						'name'  => $field_name . '_results',
81
						'value' => $value,
82
						'desc'  => false,
83
					)
84
				);
85
				if ( isset( $field->group ) ) {
86
					$store_name = str_replace( '][', '_', $field_name );
87
					$store_name = str_replace( ']', '', $store_name );
88
					$store_name = str_replace( '[', '_', $store_name );
89
90
					echo $field_type->input(
91
						array(
92
							'type'  => 'hidden',
93
							'id'    => $field_name . '_store',
94
							'name'  => $store_name . '_store',
95
							'class' => 'cmb-post-search-ajax-store',
96
							'value' => $value,
97
							'desc'  => false,
98
						)
99
					);
100
				}
101
			}
102
103
			echo $field_type->input( 
104
				array( 
105
					'type' 			=> 'text',
106
					'name' 			=> $field_name,
107
					'id'			=> $field_name,
108
					'class'			=> 'cmb-post-search-ajax',
109
					'value' 		=> $field_value,
110
					'desc'			=> false,
111
					'data-limit'	=> $field->args( 'limit' ) ? $field->args( 'limit' ) : '1',
112
					'data-sortable'	=> $field->args( 'sortable' ) ? $field->args( 'sortable' ) : '0',
113
					'data-object'	=> $field->args( 'object_type' ) ? $field->args( 'object_type' ) : 'post',
114
					'data-queryargs'=> $field->args( 'query_args' ) ? htmlspecialchars( json_encode( $field->args( 'query_args' ) ), ENT_QUOTES, 'UTF-8' ) : ''
115
				)
116
			);
117
118
			echo '<img src="' . admin_url( 'images/spinner.gif' ) . '" class="cmb-post-search-ajax-spinner" />';
119
120
			$field_type->_desc( true, true );
121
122
		}
123
124
		/**
125
		 * Optionally save the latitude/longitude values into two custom fields
126
		 */
127
		public function sanitize( $override_value, $value, $object_id, $field_args ) {
128
			$fid = '';
129
			if ( isset( $field_args['id'] ) ) {
130
				$fid = $field_args['id'];
131
			}
132
133
			// IF the field is in a repeatable group, then get the info from the post data.
134
			if ( isset( $field_args['render_row_cb'][0]->group ) && ! empty( $field_args['render_row_cb'][0]->group ) ) {
135
				$new_index = '';
136
137
				$data_to_save = $field_args['render_row_cb'][0]->group->args['render_row_cb'][0]->data_to_save;
138
				$oid          = $field_args['_name'];
139
				$iid          = $field_args['_id'];
140
				$oid          = explode( '[', $oid );
141
				if ( is_array( $oid ) ) {
142
					$oid = $oid[0];
143
				}
144
145
				if ( isset( $data_to_save[ $oid ] ) && ! empty( $data_to_save[ $oid ] ) ) {
146
					foreach( $data_to_save[ $oid ] as $index => $svalues ) {
147
						if ( isset( $svalues[ $iid ] ) && $value === $svalues[ $iid ] ) {
148
							$new_index = $index;
149
						}
150
					}
151
				}
152
153
				if ( '' !== $new_index ) {
154
					$new_index = $oid . '_' . $new_index . '_' . $iid . '_store';
155
156
					if ( ! empty( $data_to_save[ $new_index ] ) ) {
157
						$value = $data_to_save[ $new_index ];
158
					}
159
				} else {
160
					$value = false;
161
				}
162
			} else if ( ! empty( $field_args['render_row_cb'][0]->data_to_save[ $fid . '_results' ] ) ) {
163
				$value = $field_args['render_row_cb'][0]->data_to_save[ $fid . '_results' ];
164
			} else {
165
				$value = false;
166
			}
167
168
			return $value;
169
		}
170
171
		/**
172
		 * Defines the url which is used to load local resources. Based on, and uses, 
173
		 * the CMB2_Utils class from the CMB2 library.
174
		 */
175
		public static function url( $path = '' ) {
176
			if ( self::$url ) {
177
				return self::$url . $path;
178
			}
179
180
			/**
181
			 * Set the variable cmb2_fpsa_dir
182
			 */
183
			$cmb2_fpsa_dir = trailingslashit( dirname( __FILE__ ) );
184
185
			/**
186
			 * Use CMB2_Utils to gather the url from cmb2_fpsa_dir
187
			 */	
188
			$cmb2_fpsa_url = CMB2_Utils::get_url_from_dir( $cmb2_fpsa_dir );
189
190
			/**
191
			 * Filter the CMB2 FPSA location url
192
			 */
193
			self::$url = trailingslashit( apply_filters( 'cmb2_fpsa_url', $cmb2_fpsa_url, self::VERSION ) );
194
195
			return self::$url . $path;
196
		}
197
198
		/**
199
		 * Enqueue scripts and styles
200
		 */
201
		public function setup_admin_scripts() {
202
203
			wp_register_script( 'jquery-autocomplete', self::url( 'js/jquery.autocomplete.min.js' ), array( 'jquery' ), self::VERSION );
204
			wp_register_script( 'mag-post-search-ajax', self::url( 'js/mag-post-search-ajax.js' ), array( 'jquery', 'jquery-autocomplete', 'jquery-ui-sortable' ), self::VERSION );
205
			wp_localize_script( 'mag-post-search-ajax', 'psa', array(
206
				'ajaxurl' 	=> admin_url( 'admin-ajax.php' ),
207
				'nonce'		=> wp_create_nonce( 'mag_cmb_post_search_ajax_get_results' )
208
			) ); 
209
			wp_enqueue_script( 'mag-post-search-ajax' );
210
			wp_enqueue_style( 'mag-post-search-ajax', self::url( 'css/mag-post-search-ajax.css' ), array(), self::VERSION );
211
212
		}
213
214
		/**
215
		 * Ajax request : get results
216
		 */
217
		public function cmb_post_search_ajax_get_results() {
218
			$nonce = sanitize_text_field( $_POST['psacheck'] );
219
			if ( ! wp_verify_nonce( $nonce, 'mag_cmb_post_search_ajax_get_results' ) ) {
220
				die( json_encode( array( 'error' => __( 'Error : Unauthorized action' ) ) ) );
221
			} else {
222
				$args      = json_decode( stripslashes( htmlspecialchars_decode( sanitize_text_field( $_POST['query_args'] ) ) ), true );
223
				$args['s'] = sanitize_text_field( $_POST['query'] );
224
				$datas     = array();
225
				if ( $_POST['object'] == 'user' ) {
226
227
					$args['search'] = '*' . esc_attr( sanitize_text_field( $_POST['query'] ) ) . '*';
228
					$users          = new WP_User_Query( $args );
229
					$results        = $users->get_results();
230
231
					if ( ! empty( $results ) ) {
232
						foreach ( $results as $result ){
233
							$user_info = get_userdata( $result->ID );
234
							// Define filter "mag_cmb_post_search_ajax_result" to allow customize ajax results.
235
							$datas[] = apply_filters( 'mag_cmb_post_search_ajax_result', array(
236
								'value' => $user_info->display_name,
237
								'data'  => $result->ID,
238
								'guid'  => get_edit_user_link( $result->ID ),
239
							) );
240
						}
241
					}
242
				} else {
243
					$results 	= new WP_Query( $args );
244
					if ( $results->have_posts() ) :
245
						while ( $results->have_posts() ) : $results->the_post();
246
							// Define filter "mag_cmb_post_search_ajax_result" to allow customize ajax results.
247
							$datas[] = apply_filters( 'mag_cmb_post_search_ajax_result', array(
248
								'value' => get_the_title() . ' - ' . '#' . get_the_ID(),
249
								'data'	=> get_the_ID(),
250
								'guid'	=> get_edit_post_link(),
251
							) );
252
						endwhile;
253
					endif;
254
				}
255
				wp_reset_postdata();
256
				die( json_encode( $datas ) );
257
			}
258
		}
259
	}
260
}
261