Completed
Push — issues/3312 ( 6b1a83 )
by Ravinder
1313:55 queued 1307:48
created

remove_comments_from_comment_counts()   C

Complexity

Conditions 12
Paths 92

Size

Total Lines 67

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
nc 92
nop 2
dl 0
loc 67
rs 6.2933
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
/**
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.2.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.2.0
17
	 * @access private
18
	 * @var
19
	 */
20
	static private $instance;
21
22
	/**
23
	 * Comment Types.
24
	 *
25
	 * @since  2.2.0
26
	 * @access private
27
	 * @var array
28
	 */
29
	private $comment_types;
30
31
	/**
32
	 * Singleton pattern.
33
	 *
34
	 * @since  2.2.0
35
	 * @access private
36
	 */
37
	private function __construct() {
38
	}
39
40
41
	/**
42
	 * Get instance.
43
	 *
44
	 * @since  2.2.0
45
	 * @access pu
46
	 * @return Give_Comment
47
	 */
48 View Code Duplication
	public static function get_instance() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
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.2.0
61
	 * @access private
62
	 */
63
	private function init() {
64
		/**
65
		 * Filter the comment type
66
		 *
67
		 * @since 2.2.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/Update comment
83
	 *
84
	 * @since  2.2.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|WP_Error
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 new WP_Error( 'give_invalid_required_param', __( 'This comment has invalid ID or comment text or cooment type', 'give' ) );
98
		}
99
100
		$is_existing_comment = array_key_exists( 'comment_ID', $comment_args ) && ! empty( $comment_args['comment_ID'] );
101
		$action_type         = $is_existing_comment ? 'update' : 'insert';
102
103
		/**
104
		 * Fires before inserting/updating payment|donor comment.
105
		 *
106
		 * @param int    $id   Payment|Donor ID.
107
		 * @param string $note Comment text.
108
		 *
109
		 * @since 1.0
110
		 */
111
		do_action( "give_pre_{$action_type}_{$comment_type}_note", $id, $note );
112
113
		$comment_args = wp_parse_args(
114
			$comment_args,
115
			array(
116
				'comment_post_ID'      => $id,
117
				'comment_content'      => $note,
118
				'user_id'              => is_admin() ? get_current_user_id() : 0,
119
				'comment_date'         => current_time( 'mysql' ),
120
				'comment_date_gmt'     => current_time( 'mysql', 1 ),
121
				'comment_approved'     => 1,
122
				'comment_parent'       => 0,
123
				'comment_author'       => '',
124
				'comment_author_IP'    => '',
125
				'comment_author_url'   => '',
126
				'comment_author_email' => '',
127
				'comment_type'         => "give_{$comment_type}_note",
128
129
			)
130
		);
131
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
132
133
		// Check comment max length.
134
		$error = wp_check_comment_data_max_lengths( $comment_args );
135
		if( is_wp_error( $error ) ) {
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...
136
			return $error;
137
		}
138
139
		$comment_id = $is_existing_comment
140
			? wp_update_comment( $comment_args )
141
			: wp_new_comment( $comment_args, true );
142
143
		update_comment_meta( $comment_id, "_give_{$comment_type}_id", $id );
144
145
		/**
146
		 * Fires after payment|donor comment inserted/updated.
147
		 *
148
		 * @param int    $comment_id Comment ID.
149
		 * @param int    $id         Payment|Donor ID.
150
		 * @param string $note       Comment text.
151
		 *
152
		 * @since 1.0
153
		 */
154
		do_action( "give_{$action_type}_{$comment_type}_note", $comment_id, $id, $note );
155
156
		return $comment_id;
157
	}
158
159
160
	/**
161
	 * Delete comment
162
	 *
163
	 * @since  2.2.0
164
	 * @access public
165
	 *
166
	 * @param int    $comment_id   The comment ID to delete.
167
	 * @param int    $id           The payment|Donor ID the note is connected to.
168
	 * @param string $comment_type Value can ve donor|payment.
169
	 *
170
	 * @since  1.0
171
	 *
172
	 * @return bool True on success, false otherwise.
173
	 */
174
	public static function delete( $comment_id, $id, $comment_type ) {
175
		$ret = false;
176
177
		// Bailout
178
		if ( empty( $id ) || empty( $comment_id ) || empty( $comment_type ) ) {
179
			return $ret;
180
		}
181
182
		/**
183
		 * Fires before deleting donation note.
184
		 *
185
		 * @param int $comment_id Comment ID.
186
		 * @param int $id         Payment|Donor ID.
187
		 *
188
		 * @since 1.0
189
		 */
190
		do_action( "give_pre_delete_{$comment_type}_note", $comment_id, $id );
191
192
		$ret = wp_delete_comment( $comment_id, true );
193
194
		/**
195
		 * Fires after donation note deleted.
196
		 *
197
		 * @param int  $comment_id Note ID.
198
		 * @param int  $id         Payment|Donor ID.
199
		 * @param bool $ret        Flag to check if comment deleted or not.
200
		 *
201
		 * @since 1.0
202
		 */
203
		do_action( "give_post_delete_{$comment_type}_note", $comment_id, $id, $ret );
204
205
		return $ret;
206
	}
207
208
209
	/**
210
	 * Get comments
211
	 *
212
	 * @since  2.2.0
213
	 * @access public
214
	 *
215
	 * @param int    $id
216
	 * @param string $comment_type
217
	 * @param array  $comment_args
218
	 * @param string $search
219
	 *
220
	 * @return array
221
	 */
222
	public static function get( $id, $comment_type, $comment_args = array(), $search = '' ) {
223
		$comments = array();
224
225
		// Set default meta_query value.
226
		if ( ! isset( $comment_args['meta_query'] ) ) {
227
			$comment_args['meta_query'] = array();
0 ignored issues
show
introduced by
Detected usage of meta_query, possible slow query.
Loading history...
228
		}
229
230
		// Bailout
231
		if ( empty( $id ) || empty( $comment_type ) ) {
232
			return $comments;
233
		}
234
235
		remove_action( 'pre_get_comments', array( self::$instance, 'hide_comments' ), 10 );
236
		remove_filter( 'comments_clauses', array( self::$instance, 'hide_comments_pre_wp_41' ), 10 );
237
238
		switch ( $comment_type ) {
239 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...
240
				$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...
241
					? $comment_args['meta_query']
242
					: array(
243
						array(
244
							'key'     => '_give_donor_id',
245
							'compare' => 'NOT EXISTS'
246
						)
247
					);
248
249
				$comments = get_comments( wp_parse_args(
250
					$comment_args,
251
					array(
252
						'post_id' => $id,
253
						'order'   => 'ASC',
254
						'search'  => $search,
255
						'type'    => 'give_payment_note'
256
					)
257
				) );
258
				break;
259
260 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...
261
				$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...
262
					? $comment_args['meta_query']
263
					: array(
264
						array(
265
							'key'   => "_give_{$comment_type}_id",
266
							'value' => $id
267
						)
268
					);
269
270
				$comments = get_comments( wp_parse_args(
271
					$comment_args,
272
					array(
273
						'order'  => 'ASC',
274
						'search' => $search,
275
						'type'   => 'give_donor_note'
276
					)
277
				) );
278
				break;
279
		}
280
281
		add_action( 'pre_get_comments', array( self::$instance, 'hide_comments' ), 10, 1 );
282
		add_filter( 'comments_clauses', array( self::$instance, 'hide_comments_pre_wp_41' ), 10, 1 );
283
284
		return $comments;
285
	}
286
287
	/**
288
	 * Exclude comments from showing in Recent
289
	 * Comments widgets
290
	 *
291
	 * @since  2.2.0
292
	 * @access public
293
	 *
294
	 * @param object $query WordPress Comment Query Object.
295
	 *
296
	 * @return void
297
	 */
298
	public function hide_comments( $query ) {
299
		if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '>=' ) ) {
300
			$types = isset( $query->query_vars['type__not_in'] ) ? $query->query_vars['type__not_in'] : array();
301
			if ( ! is_array( $types ) ) {
302
				$types = array( $types );
303
			}
304
305
			$types = array_filter( array_merge( $types, $this->comment_types ) );
306
307
			$query->query_vars['type__not_in'] = $types;
308
		}
309
	}
310
311
	/**
312
	 * Exclude notes (comments) from showing in Recent Comments widgets
313
	 *
314
	 * @since  2.2.0
315
	 * @access public
316
	 *
317
	 * @param array $clauses Comment clauses for comment query.
318
	 *
319
	 * @return array $clauses Updated comment clauses.
320
	 */
321
	public function hide_comments_pre_wp_41( $clauses ) {
322
		if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '<' ) ) {
323
			foreach ( $this->comment_types as $comment_type ) {
324
				$clauses['where'] .= " AND comment_type != \"{$comment_type}\"";
325
			}
326
		}
327
328
		return $clauses;
329
	}
330
331
	/**
332
	 * Exclude notes (comments) from showing in comment feeds
333
	 *
334
	 * @since  2.2.0
335
	 * @access public
336
	 *
337
	 * @param string $where
338
	 *
339
	 * @return string $where
340
	 */
341
	public function hide_comments_from_feeds( $where ) {
342
		global $wpdb;
343
344
		foreach ( $this->comment_types as $comment_type ) {
345
			$where .= $wpdb->prepare( ' AND comment_type!=%s', $comment_type );
346
		}
347
348
		return $where;
349
	}
350
351
	/**
352
	 * Remove Give Comments from the wp_count_comments function
353
	 *
354
	 * @since  2.2.0
355
	 * @access public
356
	 *
357
	 * @param array $stats   (empty from core filter).
358
	 * @param int   $post_id Post ID.
359
	 *
360
	 * @return array|object Array of comment counts.
361
	 */
362
	public function remove_comments_from_comment_counts( $stats, $post_id ) {
363
		global $wpdb;
364
365
		$post_id = (int) $post_id;
366
367
		if ( apply_filters( 'give_count_payment_notes_in_comments', false ) ) {
368
			return $stats;
369
		}
370
371
		$stats = Give_Cache::get_group( "comments-{$post_id}", 'counts' );
372
373
		// Return result from cache.
374
		if ( ! is_null( $stats ) ) {
375
			return $stats;
376
		}
377
378
		$where = 'WHERE';
379
380
		foreach ( $this->comment_types as $index => $comment_type ) {
381
			$where .= ( $index ? ' AND ' : ' ' ) . "comment_type != \"{$comment_type}\"";
382
		}
383
384
		if ( $post_id > 0 ) {
385
			$where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
386
		}
387
388
		$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...
389
			"
390
				  SELECT comment_approved, COUNT( * ) AS num_comments
391
				  FROM {$wpdb->comments} {$where}
392
				  GROUP BY comment_approved
393
				  ",
394
			ARRAY_A
395
		);
396
397
		$total    = 0;
398
		$approved = array(
399
			'0'            => 'moderated',
0 ignored issues
show
introduced by
Detected usage of 0, possible slow query.
Loading history...
400
			'1'            => 'approved',
401
			'spam'         => 'spam',
402
			'trash'        => 'trash',
403
			'post-trashed' => 'post-trashed',
404
		);
405
406
		foreach ( (array) $count as $row ) {
407
			// Don't count post-trashed toward totals.
408
			if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) {
409
				$total += $row['num_comments'];
410
			}
411
			if ( isset( $approved[ $row['comment_approved'] ] ) ) {
412
				$stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
413
			}
414
		}
415
416
		$stats['total_comments'] = $stats['all'] = $total;
417
		foreach ( $approved as $key ) {
418
			if ( empty( $stats[ $key ] ) ) {
419
				$stats[ $key ] = 0;
420
			}
421
		}
422
423
		$stats = (object) $stats;
424
425
		Give_Cache::set_group( "comments-{$post_id}", $stats, 'counts' );
426
427
		return $stats;
428
	}
429
430
	/**
431
	 * Get donor name
432
	 *
433
	 * @since  2.2.0
434
	 * @access public
435
	 *
436
	 * @param string     $author
437
	 * @param int        $comment_id
438
	 * @param WP_Comment $comment
439
	 *
440
	 * @return mixed
441
	 */
442
	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...
443
		if ( in_array( $comment->comment_type, $this->comment_types ) ) {
444
			switch ( $comment->comment_type ) {
445
				case 'give_payment_note':
446
					if ( get_comment_meta( $comment_id, '_give_donor_id', true ) ) {
447
						$author = give_get_donor_name_by( $comment->comment_post_ID );
448
					}
449
			}
450
		}
451
452
		return $author;
453
	}
454
455
456
	/**
457
	 * Get comment types
458
	 *
459
	 * @since  2.2.0
460
	 * @access public
461
	 *
462
	 * @param array @comment_types
463
	 *
464
	 * @return array
465
	 */
466
	public static function get_comment_types( $comment_types ) {
467
		$_comment_types = array();
468
		foreach ( $comment_types as $comment_type ) {
469
			$_comment_types[] = "give_{$comment_type}_note";
470
		}
471
472
		return $_comment_types;
473
	}
474
}
475