Test Failed
Push — issue/2900 ( f2122b )
by Ravinder
07:32
created

Give_Comment   B

Complexity

Total Complexity 47

Size/Duplication

Total Lines 447
Duplicated Lines 8.28 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 37
loc 447
rs 8.439
c 0
b 0
f 0
wmc 47
lcom 1
cbo 1

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A get_instance() 0 8 2
A init() 0 17 1
B add() 0 52 5
B delete() 0 33 4
C get() 37 62 8
A hide_comments() 0 12 4
A hide_comments_pre_wp_41() 0 9 3
A hide_comments_from_feeds() 0 7 1
C remove_comments_from_comment_counts() 0 67 12
A __get_comment_author() 0 12 4
A get_comment_types() 0 8 2

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

1
<?php
2
3
/**
4
 * Class for managing comments
5
 *
6
 * @package     Give
7
 * @subpackage  Classes/Give_Cache
8
 * @copyright   Copyright (c) 2018, WordImpress
9
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
10
 * @since       2.1.0
11
 */
12
class Give_Comment {
0 ignored issues
show
Coding Style introduced by
Since you have declared the constructor as private, maybe you should also declare the class as final.
Loading history...
13
	/**
14
	 * Instance.
15
	 *
16
	 * @since  2.1.0
17
	 * @access private
18
	 * @var
19
	 */
20
	static private $instance;
21
22
	/**
23
	 * Comment Types.
24
	 *
25
	 * @since  2.1.0
26
	 * @access private
27
	 * @var array
28
	 */
29
	private $comment_types;
30
31
	/**
32
	 * Singleton pattern.
33
	 *
34
	 * @since  2.1.0
35
	 * @access private
36
	 */
37
	private function __construct() {
38
	}
39
40
41
	/**
42
	 * Get instance.
43
	 *
44
	 * @since  2.1.0
45
	 * @access pu
46
	 * @return Give_Comment
47
	 */
48
	public static function get_instance() {
49
		if ( null === static::$instance ) {
50
			self::$instance = new static();
51
			self::$instance->init();
52
		}
53
54
		return self::$instance;
55
	}
56
57
	/**
58
	 * Initialize
59
	 *
60
	 * @since  2.1.0
61
	 * @access private
62
	 */
63
	private function init() {
64
		/**
65
		 * Filter the comment type
66
		 *
67
		 * @since 2.1.0
68
		 */
69
		$this->comment_types = apply_filters(
70
			'give_comment_type',
71
			self::get_comment_types( array( 'payment', 'donor' ) )
72
		);
73
74
		add_action( 'pre_get_comments', array( $this, 'hide_comments' ), 10 );
75
		add_filter( 'comments_clauses', array( $this, 'hide_comments_pre_wp_41' ), 10, 1 );
76
		add_filter( 'comment_feed_where', array( $this, 'hide_comments_from_feeds' ), 10, 1 );
77
		add_filter( 'wp_count_comments', array( $this, 'remove_comments_from_comment_counts' ), 10, 2 );
78
		add_filter( 'get_comment_author', array( $this, '__get_comment_author' ), 10, 3 );
79
	}
80
81
	/**
82
	 * Insert comment
83
	 *
84
	 * @since  2.1.0
85
	 * @access public
86
	 *
87
	 * @param int    $id           Payment|Donor ID.
88
	 * @param string $note         Comment Text
89
	 * @param string $comment_type Value can ve donor|payment
90
	 * @param array  $comment_args Comment arguments
91
	 *
92
	 * @return int
93
	 */
94
	public static function add( $id, $note, $comment_type, $comment_args = array() ) {
95
		// Bailout
96
		if ( empty( $id ) || empty( $note ) || empty( $comment_type ) ) {
97
			return false;
98
		}
99
100
		/**
101
		 * Fires before inserting payment|donor comment.
102
		 *
103
		 * @param int    $id   Payment|Donor ID.
104
		 * @param string $note Comment text.
105
		 *
106
		 * @since 1.0
107
		 */
108
		do_action( "give_pre_insert_{$comment_type}_note", $id, $note );
109
110
		$comment_args = wp_parse_args(
111
			$comment_args,
112
			array(
113
				'comment_post_ID'      => $id,
114
				'comment_content'      => $note,
115
				'user_id'              => is_admin() ? get_current_user_id() : 0,
116
				'comment_date'         => current_time( 'mysql' ),
117
				'comment_date_gmt'     => current_time( 'mysql', 1 ),
118
				'comment_approved'     => 1,
119
				'comment_parent'       => 0,
120
				'comment_author'       => '',
121
				'comment_author_IP'    => '',
122
				'comment_author_url'   => '',
123
				'comment_author_email' => '',
124
				'comment_type'         => "give_{$comment_type}_note",
125
126
			)
127
		);
128
129
		$comment_id = wp_insert_comment( wp_filter_comment( $comment_args ) );
130
131
		update_comment_meta( $comment_id, "_give_{$comment_type}_id", $id );
132
133
		/**
134
		 * Fires after payment|donor comment inserted.
135
		 *
136
		 * @param int    $comment_id Comment ID.
137
		 * @param int    $id         Payment|Donor ID.
138
		 * @param string $note       Comment text.
139
		 *
140
		 * @since 1.0
141
		 */
142
		do_action( "give_insert_{$comment_type}_note", $comment_id, $id, $note );
143
144
		return $comment_id;
145
	}
146
147
148
	/**
149
	 * Delete comment
150
	 *
151
	 * @since  2.1.0
152
	 * @access public
153
	 *
154
	 * @param int    $comment_id   The comment ID to delete.
155
	 * @param int    $id           The payment|Donor ID the note is connected to.
156
	 * @param string $comment_type Value can ve donor|payment.
157
	 *
158
	 * @since  1.0
159
	 *
160
	 * @return bool True on success, false otherwise.
161
	 */
162
	public static function delete( $comment_id, $id, $comment_type ) {
163
		$ret = false;
164
165
		// Bailout
166
		if ( empty( $id ) || empty( $comment_id ) || empty( $comment_type ) ) {
167
			return $ret;
168
		}
169
170
		/**
171
		 * Fires before deleting donation note.
172
		 *
173
		 * @param int $comment_id Comment ID.
174
		 * @param int $id         Payment|Donor ID.
175
		 *
176
		 * @since 1.0
177
		 */
178
		do_action( "give_pre_delete_{$comment_type}_note", $comment_id, $id );
179
180
		$ret = wp_delete_comment( $comment_id, true );
181
182
		/**
183
		 * Fires after donation note deleted.
184
		 *
185
		 * @param int  $comment_id Note ID.
186
		 * @param int  $id         Payment|Donor ID.
187
		 * @param bool $ret        Flag to check if comment deleted or not.
188
		 *
189
		 * @since 1.0
190
		 */
191
		do_action( "give_post_delete_{$comment_type}_note", $comment_id, $id, $ret );
192
193
		return $ret;
194
	}
195
196
197
	/**
198
	 * Get comments
199
	 *
200
	 * @since  2.1.0
201
	 * @access public
202
	 *
203
	 * @param int    $id
204
	 * @param string $search
205
	 * @param string $comment_type
206
	 * @param array  $comment_args
207
	 *
208
	 * @return array
209
	 */
210
	public static function get( $id, $search = '', $comment_type, $comment_args = array() ) {
211
		$comments = array();
212
213
		// Set default meta_query value.
214
		if ( ! isset( $comment_args['meta_query'] ) ) {
215
			$comment_args['meta_query'] = array();
0 ignored issues
show
introduced by
Detected usage of meta_query, possible slow query.
Loading history...
216
		}
217
218
		// Bailout
219
		if ( empty( $id ) || empty( $comment_type ) ) {
220
			return $comments;
221
		}
222
223
		remove_action( 'pre_get_comments', array( self::$instance, 'hide_comments' ), 10 );
224
		remove_filter( 'comments_clauses', array( self::$instance, 'hide_comments_pre_wp_41' ), 10 );
225
226
		switch ( $comment_type ) {
227 View Code Duplication
			case 'payment':
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...
228
				$comment_args['meta_query'] = ! empty( $comment_args['meta_query'] )
0 ignored issues
show
introduced by
Detected usage of meta_query, possible slow query.
Loading history...
229
					? $comment_args['meta_query']
230
					: array(
231
						array(
232
							'key'     => '_give_donor_id',
233
							'compare' => 'NOT EXISTS'
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
234
						)
0 ignored issues
show
introduced by
Comma required after last value in array declaration
Loading history...
235
					);
236
237
				$comments = get_comments( wp_parse_args(
238
					$comment_args,
239
					array(
240
						'post_id' => $id,
241
						'order'   => 'ASC',
242
						'search'  => $search,
243
					)
244
				) );
245
				break;
246
247 View Code Duplication
			case 'donor':
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...
248
				$comment_args['meta_query'] = ! empty( $comment_args['meta_query'] )
0 ignored issues
show
introduced by
Detected usage of meta_query, possible slow query.
Loading history...
249
					? $comment_args['meta_query']
250
					: array(
251
						array(
252
							'key'   => "_give_{$comment_type}_id",
253
							'value' => $id
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
254
						)
0 ignored issues
show
introduced by
Comma required after last value in array declaration
Loading history...
255
					);
256
257
				$comments = get_comments( wp_parse_args(
258
					$comment_args,
259
					array(
260
						'order'  => 'ASC',
261
						'search' => $search,
262
					)
263
				) );
264
				break;
265
		}
266
267
		add_action( 'pre_get_comments', array( self::$instance, 'hide_comments' ), 10, 1 );
268
		add_filter( 'comments_clauses', array( self::$instance, 'hide_comments_pre_wp_41' ), 10, 1 );
269
270
		return $comments;
271
	}
272
273
	/**
274
	 * Exclude comments from showing in Recent
275
	 * Comments widgets
276
	 *
277
	 * @since  2.1.0
278
	 * @access public
279
	 *
280
	 * @param object $query WordPress Comment Query Object.
281
	 *
282
	 * @return void
283
	 */
284
	public function hide_comments( $query ) {
285
		if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '>=' ) ) {
286
			$types = isset( $query->query_vars['type__not_in'] ) ? $query->query_vars['type__not_in'] : array();
287
			if ( ! is_array( $types ) ) {
288
				$types = array( $types );
289
			}
290
291
			$types = array_filter( array_merge( $types, $this->comment_types ) );
292
293
			$query->query_vars['type__not_in'] = $types;
294
		}
295
	}
296
297
	/**
298
	 * Exclude notes (comments) from showing in Recent Comments widgets
299
	 *
300
	 * @since  2.1.0
301
	 * @access public
302
	 *
303
	 * @param array $clauses Comment clauses for comment query.
304
	 *
305
	 * @return array $clauses Updated comment clauses.
306
	 */
307
	public function hide_comments_pre_wp_41( $clauses ) {
308
		if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '<' ) ) {
309
			foreach ( $this->comment_types as $comment_type ) {
310
				$clauses['where'] .= " AND comment_type != \"{$comment_type}\"";
311
			}
312
		}
313
314
		return $clauses;
315
	}
316
317
	/**
318
	 * Exclude notes (comments) from showing in comment feeds
319
	 *
320
	 * @since  2.1.0
321
	 * @access public
322
	 *
323
	 * @param string $where
324
	 *
325
	 * @return string $where
326
	 */
327
	public function hide_comments_from_feeds( $where ) {
328
		global $wpdb;
329
330
		$where .= $wpdb->prepare( ' AND comment_type != %s', 'give_payment_note' );
331
332
		return $where;
333
	}
334
335
	/**
336
	 * Remove Give Comments from the wp_count_comments function
337
	 *
338
	 * @since  2.1.0
339
	 * @access public
340
	 *
341
	 * @param array $stats   (empty from core filter).
342
	 * @param int   $post_id Post ID.
343
	 *
344
	 * @return array|object Array of comment counts.
345
	 */
346
	public function remove_comments_from_comment_counts( $stats, $post_id ) {
347
		global $wpdb;
348
349
		$post_id = (int) $post_id;
350
351
		if ( apply_filters( 'give_count_payment_notes_in_comments', false ) ) {
352
			return $stats;
353
		}
354
355
		$stats = Give_Cache::get_group( "comments-{$post_id}", 'counts' );
356
357
		// Return result from cache.
358
		if ( ! is_null( $stats ) ) {
359
			return $stats;
360
		}
361
362
		$where = 'WHERE';
363
364
		foreach ( $this->comment_types as $index => $comment_type ) {
365
			$where .= ( $index ? ' AND ' : ' ' ) . "comment_type != \"{$comment_type}\"";
366
		}
367
368
		if ( $post_id > 0 ) {
369
			$where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
370
		}
371
372
		$count = $wpdb->get_results(
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
373
			"
374
				  SELECT comment_approved, COUNT( * ) AS num_comments
375
				  FROM {$wpdb->comments} {$where}
376
				  GROUP BY comment_approved
377
				  ",
378
			ARRAY_A
379
		);
380
381
		$total    = 0;
382
		$approved = array(
383
			'0'            => 'moderated',
0 ignored issues
show
introduced by
Detected usage of 0, possible slow query.
Loading history...
384
			'1'            => 'approved',
385
			'spam'         => 'spam',
386
			'trash'        => 'trash',
387
			'post-trashed' => 'post-trashed',
388
		);
389
390
		foreach ( (array) $count as $row ) {
391
			// Don't count post-trashed toward totals.
392
			if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) {
393
				$total += $row['num_comments'];
394
			}
395
			if ( isset( $approved[ $row['comment_approved'] ] ) ) {
396
				$stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
397
			}
398
		}
399
400
		$stats['total_comments'] = $stats['all'] = $total;
401
		foreach ( $approved as $key ) {
402
			if ( empty( $stats[ $key ] ) ) {
403
				$stats[ $key ] = 0;
404
			}
405
		}
406
407
		$stats = (object) $stats;
408
409
		Give_Cache::set_group( "comments-{$post_id}", $stats, 'counts' );
410
411
		return $stats;
412
	}
413
414
	/**
415
	 * Get donor name
416
	 *
417
	 * @since 2.1.0
418
	 * @access public
419
	 *
420
	 * @param string $author
421
	 * @param int $comment_id
422
	 * @param WP_Comment $comment
423
	 *
424
	 * @return mixed
425
	 */
426
	public function __get_comment_author( $author, $comment_id, $comment ) {
0 ignored issues
show
Coding Style introduced by
Method name "Give_Comment::__get_comment_author" is invalid; only PHP magic methods should be prefixed with a double underscore
Loading history...
427
		if( in_array( $comment->comment_type, $this->comment_types ) ){
0 ignored issues
show
introduced by
Space after opening control structure is required
Loading history...
introduced by
No space before opening parenthesis is prohibited
Loading history...
428
			switch ( $comment->comment_type ) {
429
				case 'give_payment_note':
430
					if ( get_comment_meta( $comment_id, '_give_donor_id', true ) ) {
431
						$author = give_get_donor_name_by( $comment->comment_post_ID );
432
					}
433
			}
434
		}
435
436
		return $author;
437
	}
438
439
440
	/**
441
	 * Get comment types
442
	 *
443
	 * @since  2.1.0
444
	 * @access public
445
	 *
446
	 * @param array @comment_types
447
	 *
448
	 * @return array
449
	 */
450
	public static function get_comment_types( $comment_types ) {
451
		$_comment_types = array();
452
		foreach ( $comment_types as $comment_type ) {
453
			$_comment_types[] = "give_{$comment_type}_note";
454
		}
455
456
		return $_comment_types;
457
	}
458
}
459