Completed
Push — add/related-posts-customize ( 4a306a...1c5144 )
by
unknown
43:30 queued 35:07
created

Milestone_Widget::widget()   C

Complexity

Conditions 13
Paths 44

Size

Total Lines 68
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 48
nc 44
nop 2
dl 0
loc 68
rs 5.761
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
Plugin Name: Milestone
4
Description: Countdown to a specific date.
5
Version: 1.0
6
Author: Automattic Inc.
7
Author URI: http://automattic.com/
8
License: GPLv2 or later
9
*/
10
11
class Jetpack_Milestone {
12
	public static function init() {
13
		add_action( 'widgets_init', array( __class__, 'register_widget' ) );
14
	}
15
	public static function register_widget() {
16
		register_widget( 'Milestone_Widget' );
17
	}
18
}
19
20
Jetpack_Milestone::init();
21
22
class Milestone_Widget extends WP_Widget {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
23
	private static $dir       = null;
24
	private static $url       = null;
25
	private static $labels    = null;
26
	private static $defaults  = null;
0 ignored issues
show
Unused Code introduced by
The property $defaults is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
27
	private static $config_js = null;
28
29
	function __construct() {
30
		$widget = array(
31
			'classname'   => 'milestone-widget',
32
			'description' => __( 'Display a countdown to a certain date.', 'jetpack' ),
33
		);
34
35
		$control = array(
36
			'width' => 251, // Chrome needs a little extra room for the date fields.
37
		);
38
39
		parent::__construct(
40
			'Milestone_Widget',
41
			/** This filter is documented in modules/widgets/facebook-likebox.php */
42
			apply_filters( 'jetpack_widget_name', __( 'Milestone', 'jetpack' ) ),
43
			$widget,
44
			$control
45
		);
46
47
		self::$dir = trailingslashit( dirname( __FILE__ ) );
48
		self::$url = plugin_dir_url( __FILE__ );
49
		self::$labels = array(
50
			'year'    => __( 'year', 'jetpack' ),
51
			'years'   => __( 'years', 'jetpack' ),
52
			'month'   => __( 'month', 'jetpack' ),
53
			'months'  => __( 'months', 'jetpack' ),
54
			'day'     => __( 'day', 'jetpack' ),
55
			'days'    => __( 'days', 'jetpack' ),
56
			'hour'    => __( 'hour', 'jetpack' ),
57
			'hours'   => __( 'hours', 'jetpack' ),
58
			'minute'  => __( 'minute', 'jetpack' ),
59
			'minutes' => __( 'minutes', 'jetpack' ),
60
			'second'  => __( 'second', 'jetpack' ),
61
			'seconds' => __( 'seconds', 'jetpack' ),
62
		);
63
64
		add_action( 'wp_enqueue_scripts', array( __class__, 'enqueue_template' ) );
65
		add_action( 'admin_enqueue_scripts', array( __class__, 'enqueue_admin' ) );
66
		add_action( 'wp_footer', array( __class__, 'localize_script' ) );
67
68
		if ( is_active_widget( false, false, $this->id_base, true ) || is_active_widget( false, false, 'monster', true ) ) {
69
			add_action( 'wp_head', array( __class__, 'styles_template' ) );
70
		}
71
	}
72
73
	public static function enqueue_admin( $hook_suffix ) {
74
		if ( 'widgets.php' == $hook_suffix ) {
75
			wp_enqueue_style( 'milestone-admin', self::$url . 'style-admin.css', array(), '20111212' );
76
		}
77
	}
78
79
	public static function enqueue_template() {
80
		wp_enqueue_script( 'milestone', self::$url . 'milestone.js', array( 'jquery' ), '20160520', true );
81
	}
82
83
	public static function styles_template() {
84
		global $themecolors;
85
		$colors = wp_parse_args( $themecolors, array(
86
			'bg'     => 'ffffff',
87
			'border' => 'cccccc',
88
			'text'   => '333333',
89
		) );
90
?>
91
<style>
92
.milestone-widget {
93
	margin-bottom: 1em;
94
}
95
.milestone-content {
96
	line-height: 2;
97
	margin-top: 5px;
98
	max-width: 17em;
99
	padding: 0;
100
	text-align: center;
101
}
102
.milestone-header {
103
	background-color: <?php echo self::sanitize_color_hex( $colors['text'] ); ?>;
104
	color: <?php echo self::sanitize_color_hex( $colors['bg'] ); ?>;
105
	line-height: 1.3;
106
	margin: 0;
107
	padding: .8em;
108
}
109
.milestone-header .event,
110
.milestone-header .date {
111
	display: block;
112
}
113
.milestone-header .event {
114
	font-size: 120%;
115
}
116
.milestone-countdown .difference {
117
	display: block;
118
	font-size: 500%;
119
	font-weight: bold;
120
	line-height: 1.2;
121
}
122
.milestone-countdown,
123
.milestone-message {
124
	background-color: <?php echo self::sanitize_color_hex( $colors['bg'] ); ?>;
125
	border: 1px solid <?php echo self::sanitize_color_hex( $colors['border'] ); ?>;
126
	border-top: 0;
127
	color: <?php echo self::sanitize_color_hex( $colors['text'] ); ?>;
128
	padding-bottom: 1em;
129
}
130
.milestone-message {
131
	padding-top: 1em
132
}
133
</style>
134
<?php
135
	}
136
137
	/**
138
	 * Ensure that a string representing a color in hexadecimal
139
	 * notation is safe for use in css and database saves.
140
	 *
141
	 * @param string Color in hexadecimal notation. "#" may or may not be prepended to the string.
142
	 * @return string Color in hexadecimal notation on success - the string "transparent" otherwise.
143
	 */
144
	public static function sanitize_color_hex( $hex, $prefix = '#' ) {
145
		$hex = trim( $hex );
146
147
		/* Strip recognized prefixes. */
148
		if ( 0 === strpos( $hex, '#' ) ) {
149
			$hex = substr( $hex, 1 );
150
		} elseif ( 0 === strpos( $hex, '%23' ) ) {
151
			$hex = substr( $hex, 3 );
152
		}
153
154
		if ( 0 !== preg_match( '/^[0-9a-fA-F]{6}$/', $hex ) ) {
155
			return $prefix . $hex;
156
		}
157
158
		return 'transparent';
159
	}
160
161
	/**
162
	 * Localize Front-end Script.
163
	 *
164
	 * Print the javascript configuration array only if the
165
	 * current template has an instance of the widget that
166
	 * is still counting down. In all other cases, this
167
	 * function will dequeue milestone.js.
168
	 *
169
	 * Hooks into the "wp_footer" action.
170
	 */
171
	function localize_script() {
172
		if ( empty( self::$config_js['instances'] ) ) {
173
			wp_dequeue_script( 'milestone' );
174
			return;
175
		}
176
		self::$config_js['labels'] = self::$labels;
177
		wp_localize_script( 'milestone', 'MilestoneConfig', self::$config_js );
178
	}
179
180
    /**
181
     * Widget
182
     */
183
    function widget( $args, $instance ) {
184
		$instance = $this->sanitize_instance( $instance );
185
186
		$milestone = mktime( $instance['hour'], $instance['min'], 0, $instance['month'], $instance['day'], $instance['year'] );
187
		$now  = (int) current_time( 'timestamp' );
188
		$diff = (int) floor( $milestone - $now );
189
190
		$number = 0;
0 ignored issues
show
Unused Code introduced by
$number is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
191
		$label  = '';
0 ignored issues
show
Unused Code introduced by
$label is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
192
193
		if ( 63113852 < $diff ) { // more than 2 years - show in years, one decimal point
194
			$number = round( $diff / 60 / 60 / 24 / 365, 1 );
195
			$label  = self::$labels['years'];
196
		} else if ( 7775999 < $diff ) { // fewer than 2 years - show in months
197
			$number = floor( $diff / 60 / 60 / 24 / 30 );
198
			$label  = ( 1 == $number ) ? self::$labels['month'] : self::$labels['months'];
199
		} else if ( 86399 < $diff ) { // fewer than 3 months - show in days
200
			$number = floor( $diff / 60 / 60 / 24 ) + 1;
201
			$label  = ( 1 == $number ) ? self::$labels['day'] : self::$labels['days'];
202
		} else if ( 3599 < $diff ) { // less than 1 day - show in hours
203
			$number = floor( $diff / 60 / 60 );
204
			$label  = ( 1 == $number ) ? self::$labels['hour'] : self::$labels['hours'];
205
		} else if ( 59 < $diff ) { // less than 1 hour - show in minutes
206
			$number = floor( $diff / 60 ) + 1;
207
			$label = ( 1 == $number ) ? self::$labels['minute'] : self::$labels['minutes'];
208
		} else { // less than 1 minute - show in seconds
209
			$number = $diff;
210
			$label = ( 1 == $number ) ? self::$labels['second'] : self::$labels['seconds'] ;
211
		}
212
213
		echo $args['before_widget'];
214
215
		$title = apply_filters( 'widget_title', $instance['title'] );
216
		if ( ! empty( $title ) ) {
217
			echo $args['before_title'] . $title . $args['after_title'];
218
		}
219
220
		echo '<div class="milestone-content">';
221
222
		echo '<div class="milestone-header">';
223
		echo '<strong class="event">' . esc_html( $instance['event'] ) . '</strong>';
224
		echo '<span class="date">' . esc_html( date_i18n( __( 'F jS, Y', 'jetpack' ), $milestone ) ) . '</span>';
225
		echo '</div>';
226
227
		if ( 1 > $diff ) {
228
			/* Milestone has past. */
229
			echo '<div class="milestone-message">' . $instance['message'] . '</div>';
230
		} else {
231
			/* Countdown to the milestone. */
232
			echo '<div class="milestone-countdown">' . sprintf( __( '%1$s %2$s to go.', 'jetpack' ),
233
				'<span class="difference">' . esc_html( $number ) . '</span>',
234
				'<span class="label">' . esc_html( $label ) . '</span>'
235
			) . '</div>';
236
237
			self::$config_js['instances'][] = array(
238
				'id'      => $args['widget_id'],
239
				'diff'    => $diff,
240
				'message' => $instance['message'],
241
			);
242
		}
243
244
		echo '</div><!--milestone-content-->';
245
246
		echo $args['after_widget'];
247
248
	    /** This action is documented in modules/widgets/gravatar-profile.php */
249
	    do_action( 'jetpack_stats_extra', 'widget_view', 'milestone' );
250
    }
251
252
    /**
253
     * Update
254
     */
255
    function update( $new_instance, $old_instance ) {
256
		return $this->sanitize_instance( $new_instance );
257
    }
258
259
	/*
260
	 * Make sure that a number is within a certain range.
261
	 * If the number is too small it will become the possible lowest value.
262
	 * If the number is too large it will become the possible highest value.
263
	 *
264
	 * @param int $n The number to check.
265
	 * @param int $floor The lowest possible value.
266
	 * @param int $ceil The highest possible value.
267
	 */
268
	function sanitize_range( $n, $floor, $ceil ) {
269
		$n = (int) $n;
270
		if ( $n < $floor ) {
271
			$n = $floor;
272
		} elseif ( $n > $ceil ) {
273
			$n = $ceil;
274
		}
275
		return $n;
276
	}
277
278
	/*
279
	 * Sanitize an instance of this widget.
280
	 *
281
	 * Date ranges match the documentation for mktime in the php manual.
282
	 * @see http://php.net/manual/en/function.mktime.php#refsect1-function.mktime-parameters
283
	 *
284
	 * @uses Milestone_Widget::sanitize_range().
285
	 */
286
	function sanitize_instance( $dirty ) {
287
		$now = (int) current_time( 'timestamp' );
288
289
		$dirty = wp_parse_args( $dirty, array(
290
			'title'   => '',
291
			'event'   => __( 'The Big Day', 'jetpack' ),
292
			'message' => __( 'The big day is here.', 'jetpack' ),
293
			'day'     => date( 'd', $now ),
294
			'month'   => date( 'm', $now ),
295
			'year'    => date( 'Y', $now ),
296
			'hour'    => 0,
297
			'min'     => 0,
298
		) );
299
300
		$allowed_tags = array(
301
			'a'      => array( 'title' => array(), 'href' => array() ),
302
			'em'     => array( 'title' => array() ),
303
			'strong' => array( 'title' => array() ),
304
		);
305
306
		$clean = array(
307
			'title'   => trim( strip_tags( stripslashes( $dirty['title'] ) ) ),
308
			'event'   => trim( strip_tags( stripslashes( $dirty['event'] ) ) ),
309
			'message' => wp_kses( $dirty['message'], $allowed_tags ),
310
			'year'    => $this->sanitize_range( $dirty['year'],  1901, 2037 ),
311
			'month'   => $this->sanitize_range( $dirty['month'], 1, 12 ),
312
			'hour'    => $this->sanitize_range( $dirty['hour'],  0, 23 ),
313
			'min'     => zeroise( $this->sanitize_range( $dirty['min'], 0, 59 ), 2 ),
314
		);
315
316
		$clean['day'] = $this->sanitize_range( $dirty['day'], 1, date( 't', mktime( 0, 0, 0, $clean['month'], 1, $clean['year'] ) ) );
317
318
		return $clean;
319
	}
320
321
    /**
322
     * Form
323
     */
324
    function form( $instance ) {
325
		$instance = $this->sanitize_instance( $instance );
326
        ?>
327
328
	<div class="milestone-widget">
329
        <p>
330
        	<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title', 'jetpack' ); ?></label>
331
        	<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $instance['title'] ); ?>" />
332
        </p>
333
334
        <p>
335
        	<label for="<?php echo $this->get_field_id( 'event' ); ?>"><?php _e( 'Event', 'jetpack' ); ?></label>
336
        	<input class="widefat" id="<?php echo $this->get_field_id( 'event' ); ?>" name="<?php echo $this->get_field_name( 'event' ); ?>" type="text" value="<?php echo esc_attr( $instance['event'] ); ?>" />
337
        </p>
338
339
		<fieldset>
340
			<legend><?php _e( 'Date and Time', 'jetpack' ); ?></legend>
341
342
			<label for="<?php echo $this->get_field_id( 'month' ); ?>" class="assistive-text"><?php _e( 'Month', 'jetpack' ); ?></label>
343
			<select id="<?php echo $this->get_field_id( 'month' ); ?>" class="month" name="<?php echo $this->get_field_name( 'month' ); ?>"><?php
344
				global $wp_locale;
345
				for ( $i = 1; $i < 13; $i++ ) {
346
					$monthnum = zeroise( $i, 2 );
347
					echo '<option value="' . esc_attr( $monthnum ) . '"' . selected( $i, $instance['month'], false ) . '>' . $monthnum . '-' . $wp_locale->get_month_abbrev( $wp_locale->get_month( $i ) ) . '</option>';
348
				}
349
			?></select>
350
351
			<label for="<?php echo $this->get_field_id( 'day' ); ?>" class="assistive-text"><?php _e( 'Day', 'jetpack' ); ?></label>
352
			<input id="<?php echo $this->get_field_id( 'day' ); ?>" class="day" name="<?php echo $this->get_field_name( 'day' ); ?>" type="text" value="<?php echo esc_attr( $instance['day'] ); ?>">,
353
354
			<label for="<?php echo $this->get_field_id( 'year' ); ?>" class="assistive-text"><?php _e( 'Year', 'jetpack' ); ?></label>
355
			<input id="<?php echo $this->get_field_id( 'year' ); ?>" class="year" name="<?php echo $this->get_field_name( 'year' ); ?>" type="text" value="<?php echo esc_attr( $instance['year'] ); ?>">
356
357
			@ <label for="<?php echo $this->get_field_id( 'hour' ); ?>" class="assistive-text"><?php _e( 'Hour', 'jetpack' ); ?></label>
358
			<input id="<?php echo $this->get_field_id( 'hour' ); ?>" class="hour" name="<?php echo $this->get_field_name( 'hour' ); ?>" type="text" value="<?php echo esc_attr( $instance['hour'] ); ?>">
359
360
			<label for="<?php echo $this->get_field_id( 'min' ); ?>" class="assistive-text"><?php _e( 'Minutes', 'jetpack' ); ?></label>
361
			: <input id="<?php echo $this->get_field_id( 'min' ); ?>" class="minutes" name="<?php echo $this->get_field_name( 'min' ); ?>" type="text" value="<?php echo esc_attr( $instance['min'] ); ?>">
362
		</fieldset>
363
364
		<p>
365
			<label for="<?php echo $this->get_field_id( 'message' ); ?>"><?php _e( 'Message', 'jetpack' ); ?></label>
366
			<textarea id="<?php echo $this->get_field_id( 'message' ); ?>" name="<?php echo $this->get_field_name( 'message' ); ?>" class="widefat"><?php echo esc_textarea( $instance['message'] ); ?></textarea>
367
		</p>
368
	</div>
369
370
		<?php
371
    }
372
}
373