Remote_Notifications_Admin   B
last analyzed

Complexity

Total Complexity 47

Size/Duplication

Total Lines 344
Duplicated Lines 1.74 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 12
Bugs 0 Features 5
Metric Value
c 12
b 0
f 5
dl 6
loc 344
rs 8.439
wmc 47
lcom 1
cbo 1

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 22 3
A get_instance() 0 9 2
A create_channel_key() 0 9 1
A delete_channel_key() 0 6 1
A generate_key() 0 11 2
B show_channel_key() 0 39 2
A metabox() 0 5 1
D notice_settings() 0 37 10
C save_settings() 0 47 8
B start_end_dates_columns() 0 22 4
C start_end_dates_columns_content() 6 51 13

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

1
<?php
2
/**
3
 * Remote Dashobard Notifications.
4
 *
5
 * @package   Remote Dashobard Notifications
6
 * @author    ThemeAvenue <[email protected]>
7
 * @license   GPL-2.0+
8
 * @link      http://themeavenue.net
9
 * @copyright 2013 ThemeAvenue
10
 */
11
12
/**
13
 * This class should ideally be used to work with the
14
 * administrative side of the WordPress site.
15
 *
16
 * @package Remote Dashobard Notifications
17
 * @author  Julien Liabeuf <[email protected]>
18
 */
19
class Remote_Notifications_Admin {
20
21
	/**
22
	 * Instance of this class.
23
	 *
24
	 * @since    1.0.0
25
	 *
26
	 * @var      object
27
	 */
28
	protected static $instance = null;
29
30
	/**
31
	 * Slug of the plugin screen.
32
	 *
33
	 * @since    1.0.0
34
	 *
35
	 * @var      string
36
	 */
37
	protected $plugin_screen_hook_suffix = null;
38
39
	/**
40
	 * Initialize the plugin by loading admin scripts & styles and adding a
41
	 * settings page and menu.
42
	 *
43
	 * @since     1.0.0
44
	 */
45
	private function __construct() {
46
47
		add_action( 'create_rn-channel', array( $this, 'create_channel_key' ), 10, 3 );
48
		add_action( 'delete_rn-channel', array( $this, 'delete_channel_key' ), 10, 3 );
49
50
		/* The rest isn't needed during Ajax */
51
		if( defined( 'DOING_AJAX' ) && DOING_AJAX )
52
			return;
53
54
		/**
55
		 * Call $plugin_slug from public plugin class.
56
		 */
57
		$plugin = Remote_Notifications::get_instance();
58
		$this->plugin_slug = $plugin->get_plugin_slug();
0 ignored issues
show
Bug introduced by
The property plugin_slug does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
59
60
		add_action( 'rn-channel_edit_form_fields', array( $this, 'show_channel_key' ), 10, 2 );
61
		add_action( 'add_meta_boxes', array( $this, 'metabox' ) );
62
		add_action( 'save_post', array( $this, 'save_settings' ) );
63
		add_filter( 'manage_notification_posts_columns', array( $this, 'start_end_dates_columns' ), 10, 1 );
64
		add_action( 'manage_notification_posts_custom_column' , array( $this, 'start_end_dates_columns_content' ), 10, 2 );
65
66
	}
67
68
	/**
69
	 * Return an instance of this class.
70
	 *
71
	 * @since     1.0.0
72
	 *
73
	 * @return    object    A single instance of this class.
74
	 */
75
	public static function get_instance() {
76
77
		// If the single instance hasn't been set, set it now.
78
		if ( null == self::$instance ) {
79
			self::$instance = new self;
80
		}
81
82
		return self::$instance;
83
	}
84
85
	/**
86
	 * Associate a key to the term created
87
	 *
88
	 * This function will save a key for each term
89
	 *
90
	 * @param int $term_id The taxonomy term ID
91
	 */
92
	public function create_channel_key( $term_id ) {
93
94
		/* Get a key */
95
		$key = $this->generate_key();
96
97
		/* Save it in DB */
98
		add_option( "_rn_channel_key_$term_id", $key );
99
100
	}
101
102
	public function delete_channel_key( $term_id ) {
103
104
		/* Save it in DB */
105
		delete_option( "_rn_channel_key_$term_id" );
106
107
	}
108
109
	private function generate_key() {
110
111
		$length = 16;
112
113
		$max = ceil($length / 40);
114
		$random = '';
115
		for ($i = 0; $i < $max; $i ++) {
116
			$random .= sha1(microtime(true).mt_rand(10000,90000));
117
		}
118
		return substr($random, 0, $length);
119
	}
120
121
	public function show_channel_key( $tag ) {  
122
123
		$term_id = $tag->term_id;
124
		$key 	 = get_option( "_rn_channel_key_$term_id", false );
125
126
		if( false === $key ) { ?>
127
128
			<tr class="form-field">  
129
				<th scope="row" valign="top">  
130
					<label><?php _e( 'Channel Key', 'remote-notifications' ); ?></label>  
131
				</th>  
132
				<td>
133
					<?php _e( 'An error occured during key generation. Please delete this channel and recreate it.', 'remote-notifications' ); ?>
134
				</td>
135
			</tr>  
136
137
			<?php return;
138
139
		}    
140
    	?>
141
    	<tr class="form-field">  
142
			<th scope="row" valign="top">  
143
				<label><?php _e( 'Channel ID', 'remote-notifications' ); ?></label>  
144
			</th>  
145
			<td>
146
				<code><?php echo $term_id; ?></code>
147
			</td>
148
		</tr>  
149
150
    	<tr class="form-field">  
151
			<th scope="row" valign="top">  
152
				<label><?php _e( 'Channel Key', 'remote-notifications' ); ?></label>  
153
			</th>  
154
			<td>
155
				<code><?php echo $key; ?></code>
156
			</td>
157
		</tr>
158
159
    <?php }
160
161
	/**
162
	* Adds a metabox to the side column on the notification screen.
163
	*/
164
	public function metabox() {
165
166
		add_meta_box( 'rn_settings', __( 'Settings', 'remote-notifications' ), array( $this, 'notice_settings' ), 'notification', 'side' );
167
168
	}
169
170
	/**
171
	* Prints the metabox content.
172
	* 
173
	* @param WP_Post $post The object for the current post/page.
174
	*/
175
	public function notice_settings( $post ) {
176
177
		wp_nonce_field( 'update_settings', 'rn_settings_nonce', false );
178
179
		/*
180
		* Use get_post_meta() to retrieve an existing value
181
		* from the database and use the value for the form.
182
		*/
183
		$value = get_post_meta( $post->ID, '_rn_settings', true );
184
		$style = isset( $value['style'] ) ? esc_attr( $value['style'] ) : '';
185
		?>
186
187
		<label for="rn_style" class="screen-reader-text"><?php _e( 'Notice Style', 'remote-notifications' ); ?></label>
188
		<p><strong><?php _e( 'Notice Style', 'remote-notification' ); ?></strong></p>
189
		<select id="rn_style" name="rn_settings[style]">
190
			<optgroup label="<?php _e( 'WordPress Style', 'remote-notifications' ); ?>">
191
				<option value="updated" <?php if( 'updated' == $style ): ?>selected="selected"<?php endif; ?>><?php _e( 'Updated', 'remote-notifications' ); ?></option>
192
				<option value="error" <?php if( 'error' == $style ): ?>selected="selected"<?php endif; ?>><?php _e( 'Error', 'remote-notifications' ); ?></option>
193
			</optgroup>
194
			<optgroup label="<?php _e( 'Custom Style', 'remote-notifications' ); ?>">
195
				<option value="success" <?php if( 'success' == $style ): ?>selected="selected"<?php endif; ?>><?php _e( 'Success', 'remote-notifications' ); ?></option>
196
				<option value="info" <?php if( 'info' == $style ): ?>selected="selected"<?php endif; ?>><?php _e( 'Info', 'remote-notifications' ); ?></option>
197
				<option value="warning" <?php if( 'warning' == $style ): ?>selected="selected"<?php endif; ?>><?php _e( 'Warning', 'remote-notifications' ); ?></option>
198
				<option value="danger" <?php if( 'danger' == $style ): ?>selected="selected"<?php endif; ?>><?php _e( 'Danger', 'remote-notifications' ); ?></option>
199
			</optgroup>
200
		</select>
201
202
		<p><label for="rn_date_start"><strong><?php _e( 'Start Date', 'remote-notifications' ); ?></strong></label></p>
203
		<input type="date" id="rn_date_start" name="rn_settings[date_start]" value="<?php echo isset( $value['date_start'] ) ? esc_attr( $value['date_start'] ) : ''; ?>">
204
		<p class="description"><?php _e( 'Leave empty for no start date (will start immediately)', 'remote-notifications' ); ?></p>
205
206
207
		<p><label for="rn_date_end"><strong><?php _e( 'End Date', 'remote-notifications' ); ?></strong></label></p>
208
		<input type="date" id="rn_date_end" name="rn_settings[date_end]" value="<?php echo isset( $value['date_end'] ) ? esc_attr( $value['date_end'] ) : ''; ?>">
209
		<p class="description"><?php _e( 'Leave empty for no end date (will never end)', 'remote-notifications' ); ?></p>
210
211
	<?php }
212
213
	/**
214
	 * When the post is saved, saves our custom data.
215
	 *
216
	 * @param int $post_id The ID of the post being saved.
217
	 *
218
	 * @return int|bool Meta ID or false on failure
219
	 */
220
	public function save_settings( $post_id ) {
221
222
		/*
223
		* We need to verify this came from the our screen and with proper authorization,
224
		* because save_post can be triggered at other times.
225
		*/
226
227
		// Check if our nonce is set.
228
		if ( ! isset( $_POST['rn_settings_nonce'] ) ) {
229
			return $post_id;
230
		}
231
232
		$nonce = $_POST['rn_settings_nonce'];
233
234
		// Verify that the nonce is valid.
235
		if ( ! wp_verify_nonce( $nonce, 'update_settings' ) ) {
236
			return $post_id;
237
		}
238
239
		// If this is an autosave, our form has not been submitted, so we don't want to do anything.
240
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
241
			return $post_id;
242
		}
243
244
		// Check the user's permissions.
245
		if ( 'notification' == $_POST['post_type'] ) {
246
247
			if ( ! current_user_can( 'edit_page', $post_id ) ) {
248
				return $post_id;
249
			}
250
251
		} else {
252
253
			if ( ! current_user_can( 'edit_post', $post_id ) ) {
254
				return $post_id;
255
			}
256
		}
257
258
		/* OK, its safe for us to save the data now. */
259
260
		// Sanitize user input.
261
		$mydata = array_map( 'sanitize_text_field', $_POST['rn_settings'] );
262
263
		// Update the meta field in the database.
264
		return update_post_meta( $post_id, '_rn_settings', $mydata );
265
266
	}
267
268
	/**
269
	 * Add start and end dates columns
270
	 *
271
	 * @since 1.2.0
272
	 *
273
	 * @param $columns
274
	 *
275
	 * @return array
276
	 */
277
	public function start_end_dates_columns( $columns ) {
278
279
		$new = array();
280
281
		foreach ( $columns as $id => $label ) {
282
283
			if ( 'date' === $id ) {
284
				$new['rn_start'] = __( 'Starts', 'remote-notifications' );
285
				$new['rn_end']   = __( 'Ends', 'remote-notifications' );
286
			}
287
288
			$new[$id] = $label;
289
290
			if ( 'title' === $id ) {
291
				$new['rn_status'] = __( 'Status', 'remote-notifications' );
292
			}
293
294
		}
295
296
		return $new;
297
298
	}
299
300
	/**
301
	 * Start and end dates columns content
302
	 *
303
	 * @since 1.2.0
304
	 *
305
	 * @param $column
306
	 * @param $post_id
307
	 *
308
	 * @return void
309
	 */
310
	public function start_end_dates_columns_content( $column, $post_id ) {
311
312
		$settings = get_post_meta( $post_id, '_rn_settings', true );
313
		$start = isset( $settings['date_start'] ) ? esc_attr( $settings['date_start'] ) : '';
314
		$end = isset( $settings['date_end'] ) ? esc_attr( $settings['date_end'] ) : '';
315
316
		switch ( $column ) {
317
318 View Code Duplication
			case 'rn_start' :
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
319
				echo ! empty( $start ) ? date( get_option( 'date_format' ), strtotime( $start ) ) : '';
320
				break;
321
322 View Code Duplication
			case 'rn_end' :
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
323
				echo ! empty( $end ) ? date( get_option( 'date_format' ), strtotime( $end ) ) : '';
324
				break;
325
326
			case 'rn_status':
327
328
				$channel = get_the_terms( $post_id, 'rn-channel' );
329
330
				if ( empty( $channel ) ) {
331
					echo '<strong>' . __( 'Won&#039;t Run', 'remote-notifications' ) . '</strong>';
332
					echo '<br><em>' . __( 'No channel set', 'remote-notifications' ) . '</em>';
333
					continue;
334
				}
335
336
				$status = '';
0 ignored issues
show
Unused Code introduced by
$status 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...
337
338
				if ( empty( $start ) || strtotime( $start ) < time() ) {
339
340
					if ( empty( $end ) ) {
341
						$status = __( '<strong>Running</strong> (endless)', 'remote-notifications' );
342
					} else {
343
344
						if ( strtotime( $end ) < time() ) {
345
							$status = __( 'Ended', 'remote-notifications' );
346
						} else {
347
							$status = '<strong>' . __( 'Running', 'remote-notifications' ) . '</strong>';
348
						}
349
					}
350
351
				} else {
352
					$status = __( 'Scheduled', 'remote-notifications' );
353
				}
354
355
				echo $status;
356
357
				break;
358
359
		}
360
	}
361
	
362
}
363