Completed
Push — fix/15025-map-block-infinite-s... ( 9a8b21...52d6c3 )
by
unknown
63:16 queued 56:01
created

Jetpack_Contact_Info_Widget   C

Complexity

Total Complexity 54

Size/Duplication

Total Lines 466
Duplicated Lines 1.72 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 8
loc 466
rs 6.4799
c 0
b 0
f 0
wmc 54
lcom 1
cbo 3

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 5 24 3
A enqueue_scripts() 0 8 1
A defaults() 0 12 1
C widget() 3 89 13
A update() 0 20 3
A build_map_link() 0 4 1
A build_map() 0 35 4
A urlencode_address() 0 9 1
B update_goodmap() 0 26 8
A has_good_map() 0 25 3
A ajax_check_api_key() 0 12 4
C form() 0 103 12

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 Jetpack_Contact_Info_Widget 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 Jetpack_Contact_Info_Widget, and based on these observations, apply Extract Interface, too.

1
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
3
use Automattic\Jetpack\Assets;
4
use Automattic\Jetpack\Redirect;
5
6
if ( ! class_exists( 'Jetpack_Contact_Info_Widget' ) ) {
7
8
	/**
9
	 * Register Contact_Info_Widget widget
10
	 */
11
	function jetpack_contact_info_widget_init() {
12
		register_widget( 'Jetpack_Contact_Info_Widget' );
13
	}
14
15
	add_action( 'widgets_init', 'jetpack_contact_info_widget_init' );
16
17
	/**
18
	 * Makes a custom Widget for displaying Restaurant Location/Map, Hours, and Contact Info available.
19
	 *
20
	 * @package WordPress
21
	 */
22
	class Jetpack_Contact_Info_Widget extends WP_Widget {
23
24
		/**
25
		 * Constructor
26
		 */
27
		public function __construct() {
28
			global $pagenow;
29
30
			$widget_ops = array(
31
				'classname'                   => 'widget_contact_info',
32
				'description'                 => __( 'Display a map with your location, hours, and contact information.', 'jetpack' ),
33
				'customize_selective_refresh' => true,
34
			);
35
			parent::__construct(
36
				'widget_contact_info',
37
				/** This filter is documented in modules/widgets/facebook-likebox.php */
38
				apply_filters( 'jetpack_widget_name', __( 'Contact Info & Map', 'jetpack' ) ),
39
				$widget_ops
40
			);
41
			$this->alt_option_name = 'widget_contact_info';
42
43 View Code Duplication
			if ( is_customize_preview() ) {
44
				add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
45
			} elseif ( 'widgets.php' === $pagenow ) {
46
				add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
47
			}
48
49
			add_action( 'wp_ajax_customize-contact-info-api-key', array( $this, 'ajax_check_api_key' ) );
50
		}
51
52
		/**
53
		 * Enqueue scripts and styles.
54
		 */
55
		public function enqueue_scripts() {
56
			wp_enqueue_style(
57
				'contact-info-map-css',
58
				plugins_url( 'contact-info/contact-info-map.css', __FILE__ ),
59
				array(),
60
				JETPACK__VERSION
61
			);
62
		}
63
64
65
		/**
66
		 * Return an associative array of default values
67
		 *
68
		 * These values are used in new widgets.
69
		 *
70
		 * @return array Array of default values for the Widget's options
71
		 */
72
		public function defaults() {
73
			return array(
74
				'title'   => __( 'Hours & Info', 'jetpack' ),
75
				'address' => __( "3999 Mission Boulevard,\nSan Diego CA 92109", 'jetpack' ),
76
				'phone'   => _x( '1-202-555-1212', 'Example of a phone number', 'jetpack' ),
77
				'hours'   => __( "Lunch: 11am - 2pm \nDinner: M-Th 5pm - 11pm, Fri-Sat:5pm - 1am", 'jetpack' ),
78
				'email'   => null,
79
				'showmap' => 0,
80
				'apikey'  => null,
81
				'goodmap' => null,
82
			);
83
		}
84
85
		/**
86
		 * Outputs the HTML for this widget.
87
		 *
88
		 * @param array $args     An array of standard parameters for widgets in this theme.
89
		 * @param array $instance An array of settings for this widget instance.
90
		 *
91
		 * @return void Echoes it's output
92
		 **/
93
		public function widget( $args, $instance ) {
94
			$instance = wp_parse_args( $instance, $this->defaults() );
0 ignored issues
show
Documentation introduced by
$this->defaults() is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
95
96
			echo $args['before_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
97
98 View Code Duplication
			if ( '' !== $instance['title'] ) {
99
				echo $args['before_title'] . esc_html( $instance['title'] ) . $args['after_title']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
100
			}
101
102
			/**
103
			 * Fires at the beginning of the Contact Info widget, after the title.
104
			 *
105
			 * @module widgets
106
			 *
107
			 * @since 3.9.2
108
			 */
109
			do_action( 'jetpack_contact_info_widget_start' );
110
111
			echo '<div itemscope itemtype="http://schema.org/LocalBusiness">';
112
113
			if ( '' !== $instance['address'] ) {
114
115
				$showmap = $instance['showmap'];
116
				$goodmap = isset( $instance['goodmap'] ) ? $instance['goodmap'] : $this->has_good_map( $instance );
117
118
				if ( $showmap && true === $goodmap ) {
119
					/**
120
					 * Set a Google Maps API Key.
121
					 *
122
					 * @since 4.1.0
123
					 *
124
					 * @param string $api_key Google Maps API Key
125
					 */
126
					$api_key = apply_filters( 'jetpack_google_maps_api_key', $instance['apikey'] );
127
					echo $this->build_map( $instance['address'], $api_key ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
128
				} elseif ( $showmap && is_customize_preview() && true !== $goodmap ) {
129
					printf(
130
						'<span class="contact-map-api-error" style="display: block;">%s</span>',
131
						esc_html( $instance['goodmap'] )
132
					);
133
				}
134
135
				$map_link = $this->build_map_link( $instance['address'] );
136
137
				printf(
138
					'<div class="confit-address" itemscope itemtype="http://schema.org/PostalAddress" itemprop="address"><a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s</a></div>',
139
					esc_url( $map_link ),
140
					str_replace( "\n", '<br/>', esc_html( $instance['address'] ) ) // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
141
				);
142
			}
143
144
			if ( '' !== $instance['phone'] ) {
145
				if ( wp_is_mobile() ) {
146
					echo '<div class="confit-phone"><span itemprop="telephone"><a href="' . esc_url( 'tel:' . $instance['phone'] ) . '">' . esc_html( $instance['phone'] ) . '</a></span></div>';
147
				} else {
148
					echo '<div class="confit-phone"><span itemprop="telephone">' . esc_html( $instance['phone'] ) . '</span></div>';
149
				}
150
			}
151
152
			if ( is_email( trim( $instance['email'] ) ) ) {
153
				printf(
154
					'<div class="confit-email"><a href="mailto:%1$s">%1$s</a></div>',
155
					esc_html( $instance['email'] )
156
				);
157
			}
158
159
			if ( '' !== $instance['hours'] ) {
160
				printf(
161
					'<div class="confit-hours" itemprop="openingHours">%s</div>',
162
					str_replace( "\n", '<br/>', esc_html( $instance['hours'] ) ) // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
163
				);
164
			}
165
166
			echo '</div>';
167
168
			/**
169
			 * Fires at the end of Contact Info widget.
170
			 *
171
			 * @module widgets
172
			 *
173
			 * @since 3.9.2
174
			 */
175
			do_action( 'jetpack_contact_info_widget_end' );
176
177
			echo $args['after_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
178
179
			/** This action is documented in modules/widgets/gravatar-profile.php */
180
			do_action( 'jetpack_stats_extra', 'widget_view', 'contact_info' );
181
		}
182
183
184
		/**
185
		 * Deals with the settings when they are saved by the admin. Here is
186
		 * where any validation should be dealt with.
187
		 *
188
		 * @param array $new_instance New configuration values.
189
		 * @param array $old_instance Old configuration values.
190
		 *
191
		 * @return array
192
		 */
193
		public function update( $new_instance, $old_instance ) {
194
195
			$instance            = array();
196
			$instance['title']   = wp_kses( $new_instance['title'], array() );
197
			$instance['address'] = wp_kses( $new_instance['address'], array() );
198
			$instance['phone']   = wp_kses( $new_instance['phone'], array() );
199
			$instance['email']   = wp_kses( $new_instance['email'], array() );
200
			$instance['hours']   = wp_kses( $new_instance['hours'], array() );
201
			$instance['apikey']  = wp_kses( isset( $new_instance['apikey'] ) ? $new_instance['apikey'] : $old_instance['apikey'], array() );
202
203
			if ( ! isset( $new_instance['showmap'] ) ) {
204
				$instance['showmap'] = 0;
205
			} else {
206
				$instance['showmap'] = intval( $new_instance['showmap'] );
207
			}
208
209
			$instance['goodmap'] = $this->update_goodmap( $old_instance, $instance );
210
211
			return $instance;
212
		}
213
214
215
		/**
216
		 * Displays the form for this widget on the Widgets page of the WP Admin area.
217
		 *
218
		 * @param array $instance Instance configuration.
219
		 *
220
		 * @return void
221
		 */
222
		public function form( $instance ) {
223
			$instance = wp_parse_args( $instance, $this->defaults() );
0 ignored issues
show
Documentation introduced by
$this->defaults() is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
224
			/** This filter is documented in modules/widgets/contact-info.php */
225
			$apikey = apply_filters( 'jetpack_google_maps_api_key', $instance['apikey'] );
226
227
			wp_enqueue_script(
228
				'contact-info-admin',
229
				Assets::get_file_url_for_environment(
230
					'_inc/build/widgets/contact-info/contact-info-admin.min.js',
231
					'modules/widgets/contact-info/contact-info-admin.js'
232
				),
233
				array( 'jquery' ),
234
				20160727,
235
				false
236
			);
237
238
			if ( is_customize_preview() ) {
239
				$customize_contact_info_api_key_nonce = wp_create_nonce( 'customize_contact_info_api_key' );
240
				wp_localize_script(
241
					'contact-info-admin',
242
					'contact_info_api_key_ajax_obj',
243
					array( 'nonce' => $customize_contact_info_api_key_nonce )
244
				);
245
			}
246
247
			?>
248
			<p>
249
				<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'Title:', 'jetpack' ); ?></label>
250
				<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $instance['title'] ); ?>" />
251
			</p>
252
253
			<p>
254
				<label for="<?php echo esc_attr( $this->get_field_id( 'address' ) ); ?>"><?php esc_html_e( 'Address:', 'jetpack' ); ?></label>
255
				<textarea class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'address' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'address' ) ); ?>"><?php echo esc_textarea( $instance['address'] ); ?></textarea>
256
			</p>
257
258
			<p>
259
				<input class="jp-contact-info-showmap" id="<?php echo esc_attr( $this->get_field_id( 'showmap' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'showmap' ) ); ?>" value="1" type="checkbox" <?php checked( $instance['showmap'], 1 ); ?> />
260
				<label for="<?php echo esc_attr( $this->get_field_id( 'showmap' ) ); ?>"><?php esc_html_e( 'Show map', 'jetpack' ); ?></label>
261
			</p>
262
263
			<?php if ( ! has_filter( 'jetpack_google_maps_api_key' ) || false === apply_filters( 'jetpack_google_maps_api_key', false ) ) { ?>
264
265
			<p class="jp-contact-info-admin-map" style="<?php echo $instance['showmap'] ? '' : 'display: none;'; ?>">
266
				<label for="<?php echo esc_attr( $this->get_field_id( 'apikey' ) ); ?>">
267
					<?php esc_html_e( 'Google Maps API Key', 'jetpack' ); ?>
268
					<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'apikey' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'apikey' ) ); ?>" type="text" value="<?php echo esc_attr( $apikey ); ?>" />
269
					<br />
270
					<small>
271
					<?php
272
					printf(
273
						wp_kses(
274
							/* Translators: placeholder is a URL to support documentation. */
275
							__( 'Google now requires an API key to use their maps on your site. <a href="%s">See our documentation</a> for instructions on acquiring a key.', 'jetpack' ),
276
							array(
277
								'a' => array(
278
									'href' => true,
279
								),
280
							)
281
						),
282
						( defined( 'IS_WPCOM' ) && IS_WPCOM ) ? 'https://wordpress.com/support/widgets/contact-info/' : esc_url( Redirect::get_url( 'jetpack-support-extra-sidebar-widgets-contact-info-widget' ) )
283
					);
284
					?>
285
					</small>
286
				</label>
287
			</p>
288
289
			<?php } else { ?>
290
291
			<input type="hidden" id="<?php echo esc_attr( $this->get_field_id( 'apikey' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'apikey' ) ); ?>" value="<?php echo esc_attr( $apikey ); ?>" />
292
293
			<?php } // end if jetpack_google_maps_api_key check. ?>
294
295
			<p class="jp-contact-info-admin-map jp-contact-info-embed-map" style="<?php echo $instance['showmap'] ? '' : 'display: none;'; ?>">
296
				<?php
297
				if ( ! is_customize_preview() && true === $instance['goodmap'] ) {
298
					echo $this->build_map( $instance['address'], $apikey ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
299
				} elseif ( true !== $instance['goodmap'] && ! empty( $instance['goodmap'] ) ) {
300
					printf(
301
						'<span class="button-link-delete">%s</span>',
302
						esc_html( $instance['goodmap'] )
303
					);
304
				}
305
				?>
306
			</p>
307
308
			<p>
309
				<label for="<?php echo esc_attr( $this->get_field_id( 'phone' ) ); ?>"><?php esc_html_e( 'Phone:', 'jetpack' ); ?></label>
310
				<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'phone' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'phone' ) ); ?>" type="text" value="<?php echo esc_attr( $instance['phone'] ); ?>" />
311
			</p>
312
313
			<p>
314
				<label for="<?php echo esc_attr( $this->get_field_id( 'email' ) ); ?>"><?php esc_html_e( 'Email Address:', 'jetpack' ); ?></label>
315
				<input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'email' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'email' ) ); ?>" type="text" value="<?php echo esc_attr( $instance['email'] ); ?>" />
316
			</p>
317
318
			<p>
319
				<label for="<?php echo esc_attr( $this->get_field_id( 'hours' ) ); ?>"><?php esc_html_e( 'Hours:', 'jetpack' ); ?></label>
320
				<textarea class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'hours' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'hours' ) ); ?>"><?php echo esc_textarea( $instance['hours'] ); ?></textarea>
321
			</p>
322
323
			<?php
324
		}
325
326
327
		/**
328
		 * Generate a Google Maps link for the supplied address.
329
		 *
330
		 * @param string $address Address to link to.
331
		 *
332
		 * @return string
333
		 */
334
		private function build_map_link( $address ) {
335
			// Google map urls have lots of available params but zoom (z) and query (q) are enough.
336
			return 'https://maps.google.com/maps?z=16&q=' . $this->urlencode_address( $address );
337
		}
338
339
340
		/**
341
		 * Builds map display HTML code from the supplied address.
342
		 *
343
		 * @param string $address Address.
344
		 * @param string $api_key API Key.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $api_key not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
345
		 *
346
		 * @return string HTML of the map.
347
		 */
348
		private function build_map( $address, $api_key = null ) {
349
			$this->enqueue_scripts();
350
			$src = add_query_arg( 'q', rawurlencode( $address ), 'https://www.google.com/maps/embed/v1/place' );
351
			if ( ! empty( $api_key ) ) {
352
				$src = add_query_arg( 'key', $api_key, $src );
353
			}
354
355
			$height = 216;
356
357
			$iframe_attributes = sprintf(
358
				' height="%d" frameborder="0" src="%s" class="contact-map"',
359
				esc_attr( $height ),
360
				esc_url( $src )
361
			);
362
363
			$iframe_html = sprintf( '<iframe width="600" %s></iframe>', $iframe_attributes );
364
365
			if (
366
				! class_exists( 'Jetpack_AMP_Support' )
367
				|| ! Jetpack_AMP_Support::is_amp_request()
368
			) {
369
				return $iframe_html;
370
			}
371
372
			$amp_iframe_html = sprintf( '<amp-iframe layout="fixed-height" width="auto" sandbox="allow-scripts allow-same-origin" %s>', $iframe_attributes );
373
374
			// Add placeholder to avoid AMP error: <amp-iframe> elements must be positioned outside the first 75% of the viewport or 600px from the top (whichever is smaller).
375
			$amp_iframe_html .= sprintf( '<span placeholder>%s</span>', esc_html__( 'Loading map&hellip;', 'jetpack' ) );
376
377
			// Add original iframe as fallback in case JavaScript is disabled.
378
			$amp_iframe_html .= sprintf( '<noscript>%s</noscript>', $iframe_html );
379
380
			$amp_iframe_html .= '</amp-iframe>';
381
			return $amp_iframe_html;
382
		}
383
384
		/**
385
		 * Encode an URL
386
		 *
387
		 * @param string $address The URL to encode.
388
		 *
389
		 * @return string The encoded URL
390
		 */
391
		private function urlencode_address( $address ) {
392
393
			$address = strtolower( $address );
394
			// Get rid of any unwanted whitespace.
395
			$address = preg_replace( '/\s+/', ' ', trim( $address ) );
396
			// Use + not %20.
397
			$address = str_ireplace( ' ', '+', $address );
398
			return rawurlencode( $address );
399
		}
400
401
		/**
402
		 * Returns the instance's updated 'goodmap' value.
403
		 *
404
		 * @param array $old_instance Old configuration values.
405
		 * @param array $instance Current configuration values.
406
		 *
407
		 * @return bool|string The instance's updated 'goodmap' value. The value is true if
408
		 * $instance can display a good map. If not, returns an error message.
409
		 */
410
		private function update_goodmap( $old_instance, $instance ) {
411
			/*
412
			 * If we have no address or don't want to show a map,
413
			 * no need to check if the map is valid.
414
			 */
415
			if ( empty( $instance['address'] ) || 0 === $instance['showmap'] ) {
416
				return false;
417
			}
418
419
			/*
420
			 * If there have been any changes that may impact the map in the widget
421
			 * (adding an address, address changes, new API key, API key change)
422
			 * then we want to check whether our map can be displayed again.
423
			 */
424
			if (
425
				! isset( $instance['goodmap'] )
426
				|| ! isset( $old_instance['address'] )
427
				|| $this->urlencode_address( $old_instance['address'] ) !== $this->urlencode_address( $instance['address'] )
428
				|| ! isset( $old_instance['apikey'] )
429
				|| $old_instance['apikey'] !== $instance['apikey']
430
			) {
431
				return $this->has_good_map( $instance );
432
			} else {
433
				return $instance['goodmap'];
434
			}
435
		}
436
437
		/**
438
		 * Check if the instance has a valid Map location.
439
		 *
440
		 * @param array $instance Widget instance configuration.
441
		 *
442
		 * @return bool|string Whether or not there is a valid map. If not, return an error message.
443
		 */
444
		private function has_good_map( $instance ) {
445
			/** This filter is documented in modules/widgets/contact-info.php */
446
			$api_key = apply_filters( 'jetpack_google_maps_api_key', $instance['apikey'] );
447
			if ( ! empty( $api_key ) ) {
448
				$path               = add_query_arg(
449
					array(
450
						'q'   => rawurlencode( $instance['address'] ),
451
						'key' => $api_key,
452
					),
453
					'https://www.google.com/maps/embed/v1/place'
454
				);
455
				$wp_remote_get_args = array(
456
					'headers' => array( 'Referer' => home_url() ),
457
				);
458
				$response           = wp_remote_get( esc_url_raw( $path ), $wp_remote_get_args );
459
460
				if ( 200 === wp_remote_retrieve_response_code( $response ) ) {
461
					return true;
462
				} else {
463
					return wp_remote_retrieve_body( $response );
464
				}
465
			}
466
467
			return __( 'Please enter a valid Google API Key.', 'jetpack' );
468
		}
469
470
		/**
471
		 * Check the Google Maps API key after an Ajax call from the widget's admin form in
472
		 * the Customizer preview.
473
		 */
474
		public function ajax_check_api_key() {
475
			if ( isset( $_POST['apikey'] ) ) {
476
				if ( check_ajax_referer( 'customize_contact_info_api_key' ) && current_user_can( 'customize' ) ) {
477
					$apikey                     = wp_kses( $_POST['apikey'], array() );
478
					$default_instance           = $this->defaults();
479
					$default_instance['apikey'] = $apikey;
480
					wp_send_json( array( 'result' => esc_html( $this->has_good_map( $default_instance ) ) ) );
481
				}
482
			} else {
483
				wp_die();
484
			}
485
		}
486
487
	}
488
489
}
490