Test Failed
Push — master ( f5256c...25a383 )
by Devin
07:02
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
		// Remove moderation emails when comment posted.
140
		remove_action( 'comment_post', 'wp_new_comment_notify_moderator' );
141
		remove_action( 'comment_post', 'wp_new_comment_notify_postauthor' );
142
143
		$comment_id = $is_existing_comment
144
			? wp_update_comment( $comment_args )
145
			: wp_new_comment( $comment_args, true );
146
147
		// Add moderation emails when comment posted.
148
		add_action( 'comment_post', 'wp_new_comment_notify_moderator' );
149
		add_action( 'comment_post', 'wp_new_comment_notify_postauthor' );
150
151
		update_comment_meta( $comment_id, "_give_{$comment_type}_id", $id );
152
153
		/**
154
		 * Fires after payment|donor comment inserted/updated.
155
		 *
156
		 * @param int    $comment_id Comment ID.
157
		 * @param int    $id         Payment|Donor ID.
158
		 * @param string $note       Comment text.
159
		 *
160
		 * @since 1.0
161
		 */
162
		do_action( "give_{$action_type}_{$comment_type}_note", $comment_id, $id, $note );
163
164
		return $comment_id;
165
	}
166
167
168
	/**
169
	 * Delete comment
170
	 *
171
	 * @since  2.2.0
172
	 * @access public
173
	 *
174
	 * @param int    $comment_id   The comment ID to delete.
175
	 * @param int    $id           The payment|Donor ID the note is connected to.
176
	 * @param string $comment_type Value can ve donor|payment.
177
	 *
178
	 * @since  1.0
179
	 *
180
	 * @return bool True on success, false otherwise.
181
	 */
182
	public static function delete( $comment_id, $id, $comment_type ) {
183
		$ret = false;
184
185
		// Bailout
186
		if ( empty( $id ) || empty( $comment_id ) || empty( $comment_type ) ) {
187
			return $ret;
188
		}
189
190
		/**
191
		 * Fires before deleting donation note.
192
		 *
193
		 * @param int $comment_id Comment ID.
194
		 * @param int $id         Payment|Donor ID.
195
		 *
196
		 * @since 1.0
197
		 */
198
		do_action( "give_pre_delete_{$comment_type}_note", $comment_id, $id );
199
200
		$ret = wp_delete_comment( $comment_id, true );
201
202
		/**
203
		 * Fires after donation note deleted.
204
		 *
205
		 * @param int  $comment_id Note ID.
206
		 * @param int  $id         Payment|Donor ID.
207
		 * @param bool $ret        Flag to check if comment deleted or not.
208
		 *
209
		 * @since 1.0
210
		 */
211
		do_action( "give_post_delete_{$comment_type}_note", $comment_id, $id, $ret );
212
213
		return $ret;
214
	}
215
216
217
	/**
218
	 * Get comments
219
	 *
220
	 * @since  2.2.0
221
	 * @access public
222
	 *
223
	 * @param int    $id
224
	 * @param string $comment_type
225
	 * @param array  $comment_args
226
	 * @param string $search
227
	 *
228
	 * @return array
229
	 */
230
	public static function get( $id, $comment_type, $comment_args = array(), $search = '' ) {
231
		$comments = array();
232
233
		// Set default meta_query value.
234
		if ( ! isset( $comment_args['meta_query'] ) ) {
235
			$comment_args['meta_query'] = array();
0 ignored issues
show
introduced by
Detected usage of meta_query, possible slow query.
Loading history...
236
		}
237
238
		// Bailout
239
		if ( empty( $id ) || empty( $comment_type ) ) {
240
			return $comments;
241
		}
242
243
		remove_action( 'pre_get_comments', array( self::$instance, 'hide_comments' ), 10 );
244
		remove_filter( 'comments_clauses', array( self::$instance, 'hide_comments_pre_wp_41' ), 10 );
245
246
		switch ( $comment_type ) {
247 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...
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_donor_id',
253
							'compare' => 'NOT EXISTS'
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
						'post_id' => $id,
261
						'order'   => 'ASC',
262
						'search'  => $search,
263
						'type'    => 'give_payment_note'
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
264
					)
265
				) );
266
				break;
267
268 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...
269
				$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...
270
					? $comment_args['meta_query']
271
					: array(
272
						array(
273
							'key'   => "_give_{$comment_type}_id",
274
							'value' => $id
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
275
						)
0 ignored issues
show
introduced by
Comma required after last value in array declaration
Loading history...
276
					);
277
278
				$comments = get_comments( wp_parse_args(
279
					$comment_args,
280
					array(
281
						'order'  => 'ASC',
282
						'search' => $search,
283
						'type'   => 'give_donor_note'
0 ignored issues
show
introduced by
Each line in an array declaration must end in a comma
Loading history...
284
					)
285
				) );
286
				break;
287
		}
288
289
		add_action( 'pre_get_comments', array( self::$instance, 'hide_comments' ), 10, 1 );
290
		add_filter( 'comments_clauses', array( self::$instance, 'hide_comments_pre_wp_41' ), 10, 1 );
291
292
		return $comments;
293
	}
294
295
	/**
296
	 * Exclude comments from showing in Recent
297
	 * Comments widgets
298
	 *
299
	 * @since  2.2.0
300
	 * @access public
301
	 *
302
	 * @param object $query WordPress Comment Query Object.
303
	 *
304
	 * @return void
305
	 */
306
	public function hide_comments( $query ) {
307
		if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '>=' ) ) {
308
			$types = isset( $query->query_vars['type__not_in'] ) ? $query->query_vars['type__not_in'] : array();
309
			if ( ! is_array( $types ) ) {
310
				$types = array( $types );
311
			}
312
313
			$types = array_filter( array_merge( $types, $this->comment_types ) );
314
315
			$query->query_vars['type__not_in'] = $types;
316
		}
317
	}
318
319
	/**
320
	 * Exclude notes (comments) from showing in Recent Comments widgets
321
	 *
322
	 * @since  2.2.0
323
	 * @access public
324
	 *
325
	 * @param array $clauses Comment clauses for comment query.
326
	 *
327
	 * @return array $clauses Updated comment clauses.
328
	 */
329
	public function hide_comments_pre_wp_41( $clauses ) {
330
		if ( version_compare( floatval( get_bloginfo( 'version' ) ), '4.1', '<' ) ) {
331
			foreach ( $this->comment_types as $comment_type ) {
332
				$clauses['where'] .= " AND comment_type != \"{$comment_type}\"";
333
			}
334
		}
335
336
		return $clauses;
337
	}
338
339
	/**
340
	 * Exclude notes (comments) from showing in comment feeds
341
	 *
342
	 * @since  2.2.0
343
	 * @access public
344
	 *
345
	 * @param string $where
346
	 *
347
	 * @return string $where
348
	 */
349
	public function hide_comments_from_feeds( $where ) {
350
		global $wpdb;
351
352
		foreach ( $this->comment_types as $comment_type ) {
353
			$where .= $wpdb->prepare( ' AND comment_type!=%s', $comment_type );
354
		}
355
356
		return $where;
357
	}
358
359
	/**
360
	 * Remove Give Comments from the wp_count_comments function
361
	 *
362
	 * @since  2.2.0
363
	 * @access public
364
	 *
365
	 * @param array $stats   (empty from core filter).
366
	 * @param int   $post_id Post ID.
367
	 *
368
	 * @return array|object Array of comment counts.
369
	 */
370
	public function remove_comments_from_comment_counts( $stats, $post_id ) {
371
		global $wpdb;
372
373
		$post_id = (int) $post_id;
374
375
		if ( apply_filters( 'give_count_payment_notes_in_comments', false ) ) {
376
			return $stats;
377
		}
378
379
		$stats = Give_Cache::get_group( "comments-{$post_id}", 'counts' );
380
381
		// Return result from cache.
382
		if ( ! is_null( $stats ) ) {
383
			return $stats;
384
		}
385
386
		$where = 'WHERE';
387
388
		foreach ( $this->comment_types as $index => $comment_type ) {
389
			$where .= ( $index ? ' AND ' : ' ' ) . "comment_type != \"{$comment_type}\"";
390
		}
391
392
		if ( $post_id > 0 ) {
393
			$where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
394
		}
395
396
		$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...
397
			"
398
				  SELECT comment_approved, COUNT( * ) AS num_comments
399
				  FROM {$wpdb->comments} {$where}
400
				  GROUP BY comment_approved
401
				  ",
402
			ARRAY_A
403
		);
404
405
		$total    = 0;
406
		$approved = array(
407
			'0'            => 'moderated',
0 ignored issues
show
introduced by
Detected usage of 0, possible slow query.
Loading history...
408
			'1'            => 'approved',
409
			'spam'         => 'spam',
410
			'trash'        => 'trash',
411
			'post-trashed' => 'post-trashed',
412
		);
413
414
		foreach ( (array) $count as $row ) {
415
			// Don't count post-trashed toward totals.
416
			if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) {
417
				$total += $row['num_comments'];
418
			}
419
			if ( isset( $approved[ $row['comment_approved'] ] ) ) {
420
				$stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
421
			}
422
		}
423
424
		$stats['total_comments'] = $stats['all'] = $total;
425
		foreach ( $approved as $key ) {
426
			if ( empty( $stats[ $key ] ) ) {
427
				$stats[ $key ] = 0;
428
			}
429
		}
430
431
		$stats = (object) $stats;
432
433
		Give_Cache::set_group( "comments-{$post_id}", $stats, 'counts' );
434
435
		return $stats;
436
	}
437
438
	/**
439
	 * Get donor name
440
	 *
441
	 * @since  2.2.0
442
	 * @access public
443
	 *
444
	 * @param string     $author
445
	 * @param int        $comment_id
446
	 * @param WP_Comment $comment
447
	 *
448
	 * @return mixed
449
	 */
450
	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...
451
		if ( in_array( $comment->comment_type, $this->comment_types ) ) {
452
			switch ( $comment->comment_type ) {
453
				case 'give_payment_note':
454
					if ( get_comment_meta( $comment_id, '_give_donor_id', true ) ) {
455
						$author = give_get_donor_name_by( $comment->comment_post_ID );
456
					}
457
			}
458
		}
459
460
		return $author;
461
	}
462
463
464
	/**
465
	 * Get comment types
466
	 *
467
	 * @since  2.2.0
468
	 * @access public
469
	 *
470
	 * @param array @comment_types
471
	 *
472
	 * @return array
473
	 */
474
	public static function get_comment_types( $comment_types ) {
475
		$_comment_types = array();
476
		foreach ( $comment_types as $comment_type ) {
477
			$_comment_types[] = "give_{$comment_type}_note";
478
		}
479
480
		return $_comment_types;
481
	}
482
}
483