Completed
Push — add/jetpack-plan-support ( c36d23...95100b )
by
unknown
14:33 queued 05:53
created

Jetpack_Contact_Info_Widget::update()   C

Complexity

Conditions 14
Paths 192

Size

Total Lines 71
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 42
nc 192
nop 2
dl 0
loc 71
rs 5.1254
c 0
b 0
f 0

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
if ( ! class_exists( 'Jetpack_Contact_Info_Widget' ) ) {
4
5
	//register Contact_Info_Widget widget
6
	function jetpack_contact_info_widget_init() {
7
		register_widget( 'Jetpack_Contact_Info_Widget' );
8
	}
9
10
	add_action( 'widgets_init', 'jetpack_contact_info_widget_init' );
11
12
	/**
13
	 * Makes a custom Widget for displaying Restaurant Location/Map, Hours, and Contact Info available.
14
	 *
15
	 * @package WordPress
16
	 */
17
	class Jetpack_Contact_Info_Widget extends WP_Widget {
18
19
		/**
20
		 * Constructor
21
		 */
22
		function __construct() {
23
			$widget_ops = array(
24
				'classname' => 'widget_contact_info',
25
				'description' => __( 'Display a map with your location, hours, and contact information.', 'jetpack' ),
26
				'customize_selective_refresh' => true,
27
			);
28
			parent::__construct(
29
				'widget_contact_info',
30
				/** This filter is documented in modules/widgets/facebook-likebox.php */
31
				apply_filters( 'jetpack_widget_name', __( 'Contact Info & Map', 'jetpack' ) ),
32
				$widget_ops
33
			);
34
			$this->alt_option_name = 'widget_contact_info';
35
36
			if ( is_customize_preview() ) {
37
				add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
38
			}
39
		}
40
41
		/**
42
		 * Enqueue scripts and styles.
43
		 */
44
		public function enqueue_scripts() {
45
			wp_enqueue_style( 'contact-info-map-css', plugins_url( 'contact-info/contact-info-map.css', __FILE__ ), null, 20160623 );
46
		}
47
48
49
		/**
50
		 * Return an associative array of default values
51
		 *
52
		 * These values are used in new widgets.
53
		 *
54
		 * @return array Array of default values for the Widget's options
55
		 */
56
		public function defaults() {
57
			return array(
58
				'title'   => __( 'Hours & Info', 'jetpack' ),
59
				'address' => __( "3999 Mission Boulevard,\nSan Diego CA 92109", 'jetpack' ),
60
				'phone'   => _x( '1-202-555-1212', 'Example of a phone number', 'jetpack' ),
61
				'hours'   => __( "Lunch: 11am - 2pm \nDinner: M-Th 5pm - 11pm, Fri-Sat:5pm - 1am", 'jetpack' ),
62
				'email'   => null,
63
				'showmap' => 0,
64
				'apikey'  => null,
65
				'lat'     => null,
66
				'lon'     => null
67
			);
68
		}
69
70
		/**
71
		 * Outputs the HTML for this widget.
72
		 *
73
		 * @param array $args     An array of standard parameters for widgets in this theme
74
		 * @param array $instance An array of settings for this widget instance
75
		 *
76
		 * @return void Echoes it's output
77
		 **/
78
		function widget( $args, $instance ) {
79
			$instance = wp_parse_args( $instance, $this->defaults() );
80
81
			echo $args['before_widget'];
82
83
			if ( '' != $instance['title'] ) {
84
				echo $args['before_title'] . $instance['title'] . $args['after_title'];
85
			}
86
87
			/**
88
			 * Fires at the beginning of the Contact Info widget, after the title.
89
			 *
90
			 * @module widgets
91
			 *
92
			 * @since 3.9.2
93
			 */
94
			do_action( 'jetpack_contact_info_widget_start' );
95
96
			if ( '' != $instance['address'] ) {
97
98
				$showmap = $instance['showmap'];
99
100
				/** This action is documented in modules/widgets/contact-info.php */
101
				if ( $showmap && $this->has_good_map( $instance ) ) {
102
					/**
103
					 * Set a Google Maps API Key.
104
					 *
105
					 * @since 4.1.0
106
					 *
107
					 * @param string $api_key Google Maps API Key
108
					 */
109
					$api_key = apply_filters( 'jetpack_google_maps_api_key', $instance['apikey'] );
110
					echo $this->build_map( $instance['address'], $api_key );
111
				}
112
113
				$map_link = $this->build_map_link( $instance['address'] );
114
115
				echo '<div class="confit-address"><a href="' . esc_url( $map_link ) . '" target="_blank">' . str_replace( "\n", "<br/>", esc_html( $instance['address'] ) ) . "</a></div>";
116
			}
117
118
			if ( '' != $instance['phone'] ) {
119
				if ( wp_is_mobile() ) {
120
					echo '<div class="confit-phone"><a href="' . esc_url( 'tel:' . $instance['phone'] ) . '">' . esc_html( $instance['phone'] ) . "</a></div>";
121
				}
122
				else {
123
					echo '<div class="confit-phone">' . esc_html( $instance['phone'] ) . '</div>';
124
				}
125
			}
126
127
			if ( is_email( $instance['email'] ) ) {
128
				printf(
129
					'<div class="confit-email"><a href="mailto:%1$s">%1$s</a></div>',
130
					esc_html( $instance['email'] )
131
				);
132
			}
133
134
			if ( '' != $instance['hours'] ) {
135
				echo '<div class="confit-hours">' . str_replace( "\n", "<br/>", esc_html( $instance['hours'] ) ) . "</div>";
136
			}
137
138
			/**
139
			 * Fires at the end of Contact Info widget.
140
			 *
141
			 * @module widgets
142
			 *
143
			 * @since 3.9.2
144
			 */
145
			do_action( 'jetpack_contact_info_widget_end' );
146
147
			echo $args['after_widget'];
148
149
			/** This action is documented in modules/widgets/gravatar-profile.php */
150
			do_action( 'jetpack_stats_extra', 'widget_view', 'contact_info' );
151
		}
152
153
154
		/**
155
		 * Deals with the settings when they are saved by the admin. Here is
156
		 * where any validation should be dealt with.
157
		 *
158
		 * @param array $new_instance New configuration values
159
		 * @param array $old_instance Old configuration values
160
		 *
161
		 * @return array
162
		 */
163
		function update( $new_instance, $old_instance ) {
164
			$update_lat_lon = false;
165
			if (
166
				! isset( $old_instance['address'] ) ||
167
				$this->urlencode_address( $old_instance['address'] ) != $this->urlencode_address( $new_instance['address'] )
168
			) {
169
				$update_lat_lon = true;
170
			}
171
172
			$instance            = array();
173
			$instance['title']   = wp_kses( $new_instance['title'], array() );
174
			$instance['address'] = wp_kses( $new_instance['address'], array() );
175
			$instance['phone']   = wp_kses( $new_instance['phone'], array() );
176
			$instance['email']   = wp_kses( $new_instance['email'], array() );
177
			$instance['hours']   = wp_kses( $new_instance['hours'], array() );
178
			$instance['apikey']  = wp_kses( isset( $new_instance['apikey'] ) ? $new_instance['apikey'] : $old_instance['apikey'], array() );
179
			$instance['lat']     = isset( $old_instance['lat'] ) ? floatval( $old_instance['lat'] ) : 0;
180
			$instance['lon']     = isset( $old_instance['lon'] ) ? floatval( $old_instance['lon'] ) : 0;
181
182
			if ( ! $instance['lat'] || ! $instance['lon'] ) {
183
				$update_lat_lon = true;
184
			}
185
186
			if ( $instance['address'] && $update_lat_lon ) {
187
188
				// Get the lat/lon of the user specified address.
189
				$address = $this->urlencode_address( $instance['address'] );
190
				$path    = "https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=" . $address;
191
				/** This action is documented in modules/widgets/contact-info.php */
192
				$key = apply_filters( 'jetpack_google_maps_api_key', $instance['apikey'] );
193
194
				if ( ! empty( $key ) ) {
195
					$path = add_query_arg( 'key', $key, $path );
196
				}
197
				$json    = wp_remote_retrieve_body( wp_remote_get( esc_url( $path, null, null ) ) );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 4 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
198
199
				if ( ! $json ) {
200
					// The read failed :(
201
					esc_html_e( "There was a problem getting the data to display this address on a map.  Please refresh your browser and try again.", 'jetpack' );
202
					die();
0 ignored issues
show
Coding Style Compatibility introduced by
The method update() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
203
				}
204
205
				$json_obj = json_decode( $json );
206
207
				if ( "ZERO_RESULTS" == $json_obj->status ) {
208
					// The address supplied does not have a matching lat / lon.
209
					// No map is available.
210
					$instance['lat'] = "0";
211
					$instance['lon'] = "0";
212
				}
213
				else {
214
215
					$loc = $json_obj->results[0]->geometry->location;
216
217
					$lat = floatval( $loc->lat );
218
					$lon = floatval( $loc->lng );
219
220
					$instance['lat'] = "$lat";
221
					$instance['lon'] = "$lon";
222
				}
223
			}
224
225
			if ( ! isset( $new_instance['showmap'] ) ) {
226
				$instance['showmap'] = 0;
227
			}
228
			else {
229
				$instance['showmap'] = intval( $new_instance['showmap'] );
230
			}
231
232
			return $instance;
233
		}
234
235
236
		/**
237
		 * Displays the form for this widget on the Widgets page of the WP Admin area.
238
		 *
239
		 * @param array $instance Instance configuration.
240
		 *
241
		 * @return void
242
		 */
243
		function form( $instance ) {
244
			$instance = wp_parse_args( $instance, $this->defaults() );
245
			wp_enqueue_script( 'contact-info-admin', plugins_url( 'contact-info/contact-info-admin.js', __FILE__ ), array( 'jquery' ), 20160727 );
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
				<?php
257
				if ( $this->has_good_map( $instance ) ) {
258
					?>
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
					<?php
262
				}
263
				else {
264
					?>
265
					<span class="error-message"><?php _e( 'Sorry. We can not plot this address. A map will not be displayed. Is the address formatted correctly?', 'jetpack' ); ?></span>
266
					<input id="<?php echo esc_attr( $this->get_field_id( 'showmap' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'showmap' ) ); ?>" value="<?php echo( intval( $instance['showmap'] ) ); ?>" type="hidden" />
267
					<?php
268
				}
269
				?>
270
			</p>
271
272
			<p class="jp-contact-info-apikey" style="<?php echo $instance['showmap'] ? '' : 'display: none;'; ?>">
273
				<label for="<?php echo esc_attr( $this->get_field_id( 'apikey' ) ); ?>">
274
					<?php _e( 'Google Maps API Key', 'jetpack' ); ?>
275
					<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( $instance['apikey'] ); ?>" />
276
					<br />
277
					<small><?php printf( wp_kses( __( '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' ), array( 'a' => array( 'href' => true ) ) ), 'https://jetpack.com/support/extra-sidebar-widgets/contact-info-widget/' ); ?></small>
278
				</label>
279
			</p>
280
281
			<p>
282
				<label for="<?php echo esc_attr( $this->get_field_id( 'phone' ) ); ?>"><?php esc_html_e( 'Phone:', 'jetpack' ); ?></label>
283
				<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'] ); ?>" />
284
			</p>
285
286
			<p>
287
				<label for="<?php echo esc_attr( $this->get_field_id( 'email' ) ); ?>"><?php esc_html_e( 'Email Address:', 'jetpack' ); ?></label>
288
				<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'] ); ?>" />
289
			</p>
290
291
			<p>
292
				<label for="<?php echo esc_attr( $this->get_field_id( 'hours' ) ); ?>"><?php esc_html_e( 'Hours:', 'jetpack' ); ?></label>
293
				<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>
294
			</p>
295
296
			<?php
297
		}
298
299
300
		/**
301
		 * Generate a Google Maps link for the supplied address.
302
		 *
303
		 * @param string $address Address to link to.
304
		 *
305
		 * @return string
306
		 */
307
		function build_map_link( $address ) {
308
			// Google map urls have lots of available params but zoom (z) and query (q) are enough.
309
			return "https://maps.google.com/maps?z=16&q=" . $this->urlencode_address( $address );
310
		}
311
312
313
		/**
314
		 * Builds map display HTML code from the supplied latitude and longitude.
315
		 *
316
		 * @param float $lat Map Latitude
0 ignored issues
show
Bug introduced by
There is no parameter named $lat. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
317
		 * @param float $lon Map Longitude
0 ignored issues
show
Bug introduced by
There is no parameter named $lon. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
318
		 *
319
		 * @return string HTML of the map
320
		 */
321
		function build_map( $address, $api_key = null ) {
322
			$this->enqueue_scripts();
323
			$src = add_query_arg( 'q', urlencode( $address ), 'https://www.google.com/maps/embed/v1/place' );
324
			if ( ! empty( $api_key ) ) {
325
				$src = add_query_arg( 'key', $api_key, $src );
326
			}
327
328
			return '<iframe width="600" height="216" frameborder="0" src="' . esc_url( $src ) . '" class="contact-map"></iframe>';
329
		}
330
331
		/**
332
		 * Encode an URL
333
		 *
334
		 * @param string $address The URL to encode
335
		 *
336
		 * @return string The encoded URL
337
		 */
338
		function urlencode_address( $address ) {
339
340
			$address = strtolower( $address );
341
			$address = preg_replace( "/\s+/", " ", trim( $address ) ); // Get rid of any unwanted whitespace
342
			$address = str_ireplace( " ", "+", $address ); // Use + not %20
343
			urlencode( $address );
344
345
			return $address;
346
		}
347
348
		/**
349
		 * Check if the instance has a valid Map location.
350
		 *
351
		 * @param array $instance Widget instance configuration.
352
		 *
353
		 * @return bool Whether or not there is a valid map.
354
		 */
355
		function has_good_map( $instance ) {
356
			// The lat and lon of an address that could not be plotted will have values of 0 and 0.
357
			return ! ( "0" == $instance['lat'] && "0" == $instance['lon'] );
358
		}
359
360
	}
361
362
}
363