Passed
Push — add/multiplan ( f03a15...eb47db )
by Chris
04:55
created

MAG_CMB2_Field_Post_Search_Ajax::render()   D

Complexity

Conditions 22
Paths 26

Size

Total Lines 107
Code Lines 79

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 22
eloc 79
c 5
b 0
f 0
nc 26
nop 5
dl 0
loc 107
rs 4.1666

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.1';
17
18
		/**
19
		 * The url which is used to load local resources
20
		 * 
21
		 * @var string
22
		 */
23
		protected static $url = '';
24
25
		/**
26
		 * Holds class instance
27
		 *
28
		 * @since 1.0.0
29
		 *
30
		 * @var      object \MAG_CMB2_Field_Post_Search_Ajax
31
		 */
32
		protected static $instance = null;
33
34
		/**
35
		 * Initialize the plugin by hooking into CMB2
36
		 */
37
		public function __construct() {
38
			add_action( 'cmb2_render_post_search_ajax', array( $this, 'render' ), 10, 5 );
39
			add_action( 'cmb2_sanitize_post_search_ajax', array( $this, 'sanitize' ), 10, 4 );
40
			add_action( 'wp_ajax_cmb_post_search_ajax_get_results', array( $this, 'cmb_post_search_ajax_get_results' ) );
41
		}
42
43
		/**
44
		 * Return an instance of this class.
45
		 *
46
		 * @since 1.0.0
47
		 *
48
		 * @return    object \MAG_CMB2_Field_Post_Search_Ajax    A single instance of this class.
49
		 */
50
		public static function get_instance() {
51
			// If the single instance hasn't been set, set it now.
52
			if ( null === self::$instance ) {
53
				self::$instance = new self();
54
			}
55
			return self::$instance;
56
		}
57
58
		/**
59
		 * Render field
60
		 */
61
		public function render( $field, $value, $object_id, $object_type, $field_type ) {	
62
			$this->setup_admin_scripts();
63
			$field_name = $field->_name();
64
65
			if ( $field->args( 'limit' ) > 1 ) {
66
				echo '<ul class="cmb-post-search-ajax-results" id="' . $field_name . '_results">';
67
				if ( isset( $value ) && ! empty( $value ) ) {
68
69
					if ( ! is_array( $value ) ) {
70
						$value = explode( ',', $value );
71
					}
72
					if ( ! is_array( $value ) ) {
73
						$value = array( $value );
74
					}
75
					$value = array_unique( $value );
76
					foreach ( $value as $val ) {
77
						$handle = ( $field->args( 'sortable' ) ) ? '<span class="hndl"></span>' : '';
78
						$li_css = '';
79
						if ( $field->args( 'object_type' ) == 'user' ) {
80
							$guid  = get_edit_user_link( $val );
81
							$user  = get_userdata( $val );
82
							$title = $user->display_name;
83
						} else {
84
							$guid  = get_edit_post_link( $val );
85
							$title = get_the_title( $val ) . ' - ' . '#' . $val;
86
							if ( 'trash' === get_post_status( $val ) ) {
87
								$li_css = 'display:none;';
88
							}
89
							$post_parent = wp_get_post_parent_id( $val );
90
							if ( 0 !== $post_parent && false !== $post_parent ) {
91
								$title = get_the_title( $post_parent ) . ' -> ' . $title;
92
							}
93
						}
94
						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>';
95
					}
96
				}
97
				echo '</ul>';
98
				$field_value = '';
99
				if ( isset( $field->group ) ) {
100
					$store_name = str_replace( '][', '_', $field_name );
101
					$store_name = str_replace( ']', '', $store_name );
102
					$store_name = str_replace( '[', '_', $store_name );
103
104
					echo $field_type->input(
105
						array(
106
							'type'  => 'hidden',
107
							'id'    => $field_name . '_store',
108
							'name'  => $store_name . '_store',
109
							'class' => 'cmb-post-search-ajax-store',
110
							'value' => implode( ',', $value ),
111
							'desc'  => false,
112
						)
113
					);
114
				}
115
			} else {
116
				if ( is_array( $value ) ) {
117
					$value = $value[0];
118
				}
119
				if ( $field->args( 'object_type' ) == 'user' ) {
120
					$field_value = ( $value ? get_userdata( $value )->display_name : '' );
121
				} else {
122
					$field_value = ( $value ? get_the_title( $value ) : '' );
123
				}
124
				echo $field_type->input( 
125
					array(
126
						'type'  => 'hidden',
127
						'name'  => $field_name . '_results',
128
						'value' => $value,
129
						'desc'  => false,
130
					)
131
				);
132
				if ( isset( $field->group ) ) {
133
					$store_name = str_replace( '][', '_', $field_name );
134
					$store_name = str_replace( ']', '', $store_name );
135
					$store_name = str_replace( '[', '_', $store_name );
136
137
					echo $field_type->input(
138
						array(
139
							'type'  => 'hidden',
140
							'id'    => $field_name . '_store',
141
							'name'  => $store_name . '_store',
142
							'class' => 'cmb-post-search-ajax-store',
143
							'value' => $value,
144
							'desc'  => false,
145
						)
146
					);
147
				}
148
			}
149
150
			echo $field_type->input( 
151
				array( 
152
					'type' 			=> 'text',
153
					'name' 			=> $field_name,
154
					'id'			=> $field_name,
155
					'class'			=> 'cmb-post-search-ajax',
156
					'value' 		=> $field_value,
157
					'desc'			=> false,
158
					'data-limit'	=> $field->args( 'limit' ) ? $field->args( 'limit' ) : '1',
159
					'data-sortable'	=> $field->args( 'sortable' ) ? $field->args( 'sortable' ) : '0',
160
					'data-object'	=> $field->args( 'object_type' ) ? $field->args( 'object_type' ) : 'post',
161
					'data-queryargs'=> $field->args( 'query_args' ) ? htmlspecialchars( json_encode( $field->args( 'query_args' ) ), ENT_QUOTES, 'UTF-8' ) : ''
162
				)
163
			);
164
165
			echo '<img src="' . admin_url( 'images/spinner.gif' ) . '" class="cmb-post-search-ajax-spinner" />';
166
167
			$field_type->_desc( true, true );
168
169
		}
170
171
		/**
172
		 * Optionally save the latitude/longitude values into two custom fields
173
		 */
174
		public function sanitize( $override_value, $value, $object_id, $field_args ) {
175
			$fid = '';
176
			if ( isset( $field_args['id'] ) ) {
177
				$fid = $field_args['id'];
178
			}
179
180
			// IF the field is in a repeatable group, then get the info from the post data.
181
			if ( isset( $field_args['render_row_cb'][0]->group ) && ! empty( $field_args['render_row_cb'][0]->group ) ) {
182
				$new_index    = '';
183
				$data_to_save = $field_args['render_row_cb'][0]->group->args['render_row_cb'][0]->data_to_save;
184
				$oid          = $field_args['_name'];
185
				$iid          = $field_args['_id'];
186
				$oid          = explode( '[', $oid );
187
188
				if ( is_array( $oid ) ) {
189
					$oid = $oid[0];
190
				}
191
192
				if ( isset( $data_to_save[ $oid ] ) && ! empty( $data_to_save[ $oid ] ) ) {
193
					foreach( $data_to_save[ $oid ] as $index => $svalues ) {
194
						if ( isset( $svalues[ $iid ] ) && $value === $svalues[ $iid ] ) {
195
							$new_index = $index;
196
						}
197
					}
198
				}
199
200
				if ( isset( $field_args['render_row_cb'][0]->group->index ) ) {
201
					$new_index = $field_args['render_row_cb'][0]->group->index;
202
				}
203
204
				if ( '' !== $new_index ) {
205
					$new_index = $oid . '_' . $new_index . '_' . $iid . '_store';
206
					if ( ! empty( $data_to_save[ $new_index ] ) ) {
207
						$value = $data_to_save[ $new_index ];
208
					}
209
				} else {
210
					$value = false;
211
				}
212
			} else if ( ! empty( $field_args['render_row_cb'][0]->data_to_save[ $fid . '_results' ] ) ) {
213
				$value = $field_args['render_row_cb'][0]->data_to_save[ $fid . '_results' ];
214
			} else if ( ! empty( $field_args['render_row_cb'][0]->data_to_save[ $fid . '_store' ] ) ) {
215
				$value = $field_args['render_row_cb'][0]->data_to_save[ $fid . '_store' ];
216
			} else {
217
				$value = false;
218
			}
219
220
			/*print_r( '<pre>' );
221
			print_r( 'FID' . $fid );
222
			print_r( '</pre>' );
223
224
			print_r( '<pre>' );
225
			print_r( 'OID' . $oid );
226
			print_r( '</pre>' );
227
228
			print_r( '<pre>' );
229
			print_r( 'IID' . $iid );
230
			print_r( '</pre>' );
231
232
			print_r( '<pre>' );
233
			print_r( 'Value' );
234
			print_r( $value );
235
			print_r( '</pre>' );*/
236
237
			return $value;
238
		}
239
240
		/**
241
		 * Defines the url which is used to load local resources. Based on, and uses, 
242
		 * the CMB2_Utils class from the CMB2 library.
243
		 */
244
		public static function url( $path = '' ) {
245
			if ( self::$url ) {
246
				return self::$url . $path;
247
			}
248
249
			/**
250
			 * Set the variable cmb2_fpsa_dir
251
			 */
252
			$cmb2_fpsa_dir = trailingslashit( dirname( __FILE__ ) );
253
254
			/**
255
			 * Use CMB2_Utils to gather the url from cmb2_fpsa_dir
256
			 */	
257
			$cmb2_fpsa_url = CMB2_Utils::get_url_from_dir( $cmb2_fpsa_dir );
258
259
			/**
260
			 * Filter the CMB2 FPSA location url
261
			 */
262
			self::$url = trailingslashit( apply_filters( 'cmb2_fpsa_url', $cmb2_fpsa_url, self::VERSION ) );
263
264
			return self::$url . $path;
265
		}
266
267
		/**
268
		 * Enqueue scripts and styles
269
		 */
270
		public function setup_admin_scripts() {
271
272
			wp_register_script( 'jquery-devautocomplete', self::url( 'js/jquery.autocomplete.min.js' ), array( 'jquery' ), self::VERSION );
273
			wp_register_script( 'mag-post-search-ajax', self::url( 'js/mag-post-search-ajax.js' ), array( 'jquery', 'jquery-devautocomplete', 'jquery-ui-sortable' ), self::VERSION );
274
			wp_localize_script( 'mag-post-search-ajax', 'psa', array(
275
				'ajaxurl' 	=> admin_url( 'admin-ajax.php' ),
276
				'nonce'		=> wp_create_nonce( 'mag_cmb_post_search_ajax_get_results' )
277
			) ); 
278
			wp_enqueue_script( 'mag-post-search-ajax' );
279
			wp_enqueue_style( 'mag-post-search-ajax', self::url( 'css/mag-post-search-ajax.css' ), array(), self::VERSION );
280
281
		}
282
283
		/**
284
		 * Ajax request : get results
285
		 */
286
		public function cmb_post_search_ajax_get_results() {
287
			$nonce = sanitize_text_field( $_POST['psacheck'] );
288
			if ( ! wp_verify_nonce( $nonce, 'mag_cmb_post_search_ajax_get_results' ) ) {
289
				die( json_encode( array( 'error' => __( 'Error : Unauthorized action' ) ) ) );
290
			} else {
291
				$args      = json_decode( stripslashes( htmlspecialchars_decode( sanitize_text_field( $_POST['query_args'] ) ) ), true );
292
				$args['s'] = sanitize_text_field( $_POST['query'] );
293
				$datas     = array();
294
				if ( $_POST['object'] == 'user' ) {
295
296
					$args['search'] = '*' . esc_attr( sanitize_text_field( $_POST['query'] ) ) . '*';
297
					$users          = new WP_User_Query( $args );
298
					$results        = $users->get_results();
299
300
					if ( ! empty( $results ) ) {
301
						foreach ( $results as $result ){
302
							$user_info = get_userdata( $result->ID );
303
							// Define filter "mag_cmb_post_search_ajax_result" to allow customize ajax results.
304
							$datas[] = apply_filters( 'mag_cmb_post_search_ajax_result', array(
305
								'value' => $user_info->display_name,
306
								'data'  => $result->ID,
307
								'guid'  => get_edit_user_link( $result->ID ),
308
							) );
309
						}
310
					}
311
				} else {
312
					$results 	= new WP_Query( $args );
313
					if ( $results->have_posts() ) :
314
						while ( $results->have_posts() ) : $results->the_post();
315
							// Define filter "mag_cmb_post_search_ajax_result" to allow customize ajax results.
316
317
							$title       = get_the_title() . ' - ' . '#' . get_the_ID();
318
							$post_parent = wp_get_post_parent_id( get_the_ID() );
319
							if ( 0 !== $post_parent && false !== $post_parent ) {
320
								$title = get_the_title( $post_parent ) . ' -> ' . $title;
321
							}
322
323
							$datas[] = apply_filters( 'mag_cmb_post_search_ajax_result', array(
324
								'value' => $title,
325
								'data'	=> get_the_ID(),
326
								'guid'	=> get_edit_post_link(),
327
							) );
328
						endwhile;
329
					endif;
330
				}
331
				wp_reset_postdata();
332
				die( json_encode( $datas ) );
333
			}
334
		}
335
	}
336
}
337