Completed
Push — add/user-authentication ( ef8545...069685 )
by Marin
06:51
created

Comments   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 357
Duplicated Lines 4.48 %

Coupling/Cohesion

Components 3
Dependencies 2

Importance

Changes 0
Metric Value
dl 16
loc 357
rs 9.92
c 0
b 0
f 0
wmc 31
lcom 3
cbo 2

18 Methods

Rating   Name   Duplication   Size   Complexity  
A name() 0 3 1
A get_object_by_id() 0 11 3
A handle_comment_contents_modification() 0 28 4
A init_full_sync_listeners() 0 3 1
A init_listeners() 0 30 3
A init_before_send() 0 19 3
A enqueue_full_sync_actions() 0 4 1
A estimate_full_sync_actions() 16 16 2
A get_where_sql() 0 7 2
A get_full_sync_actions() 0 3 1
A count_full_sync_actions() 0 3 1
A expand_wp_comment_status_change() 0 3 1
A expand_wp_insert_comment() 0 3 1
A filter_comment() 0 26 2
A is_whitelisted_comment_meta() 0 3 1
A filter_meta() 0 3 2
A expand_comment_ids() 0 17 1
A get_whitelisted_comment_types() 0 13 1

How to fix   Duplicated Code   

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:

1
<?php
2
/**
3
 * Comments sync module.
4
 *
5
 * @package automattic/jetpack-sync
6
 */
7
8
namespace Automattic\Jetpack\Sync\Modules;
9
10
use Automattic\Jetpack\Sync\Settings;
11
12
/**
13
 * Class to handle sync for comments.
14
 */
15
class Comments extends Module {
16
	/**
17
	 * Sync module name.
18
	 *
19
	 * @access public
20
	 *
21
	 * @return string
22
	 */
23
	public function name() {
24
		return 'comments';
25
	}
26
27
	/**
28
	 * Retrieve a comment by its ID.
29
	 *
30
	 * @access public
31
	 *
32
	 * @param string $object_type Type of the sync object.
33
	 * @param int    $id          ID of the sync object.
34
	 * @return \WP_Comment|bool Filtered \WP_Comment object, or false if the object is not a comment.
35
	 */
36
	public function get_object_by_id( $object_type, $id ) {
37
		$comment_id = intval( $id );
38
		if ( 'comment' === $object_type ) {
39
			$comment = get_comment( $comment_id );
40
			if ( $comment ) {
41
				return $this->filter_comment( $comment );
42
			}
43
		}
44
45
		return false;
46
	}
47
48
	/**
49
	 * Initialize comments action listeners.
50
	 * Also responsible for initializing comment meta listeners.
51
	 *
52
	 * @access public
53
	 *
54
	 * @param callable $callable Action handler callable.
55
	 */
56
	public function init_listeners( $callable ) {
57
		add_action( 'wp_insert_comment', $callable, 10, 2 );
58
		add_action( 'deleted_comment', $callable );
59
		add_action( 'trashed_comment', $callable );
60
		add_action( 'spammed_comment', $callable );
61
		add_action( 'trashed_post_comments', $callable, 10, 2 );
62
		add_action( 'untrash_post_comments', $callable );
63
		add_action( 'comment_approved_to_unapproved', $callable );
64
		add_action( 'comment_unapproved_to_approved', $callable );
65
		add_action( 'jetpack_modified_comment_contents', $callable, 10, 2 );
66
		add_action( 'untrashed_comment', $callable, 10, 2 );
67
		add_action( 'unspammed_comment', $callable, 10, 2 );
68
		add_filter( 'wp_update_comment_data', array( $this, 'handle_comment_contents_modification' ), 10, 3 );
69
70
		/**
71
		 * Even though it's messy, we implement these hooks because
72
		 * the edit_comment hook doesn't include the data
73
		 * so this saves us a DB read for every comment event.
74
		 */
75
		foreach ( $this->get_whitelisted_comment_types() as $comment_type ) {
76
			foreach ( array( 'unapproved', 'approved' ) as $comment_status ) {
77
				$comment_action_name = "comment_{$comment_status}_{$comment_type}";
78
				add_action( $comment_action_name, $callable, 10, 2 );
79
			}
80
		}
81
82
		// Listen for meta changes.
83
		$this->init_listeners_for_meta_type( 'comment', $callable );
84
		$this->init_meta_whitelist_handler( 'comment', array( $this, 'filter_meta' ) );
85
	}
86
87
	/**
88
	 * Handler for any comment content updates.
89
	 *
90
	 * @access public
91
	 *
92
	 * @param array $new_comment              The new, processed comment data.
93
	 * @param array $old_comment              The old, unslashed comment data.
94
	 * @param array $new_comment_with_slashes The new, raw comment data.
95
	 * @return array The new, processed comment data.
96
	 */
97
	public function handle_comment_contents_modification( $new_comment, $old_comment, $new_comment_with_slashes ) {
98
		$changes        = array();
99
		$content_fields = array(
100
			'comment_author',
101
			'comment_author_email',
102
			'comment_author_url',
103
			'comment_content',
104
		);
105
		foreach ( $content_fields as $field ) {
106
			if ( $new_comment_with_slashes[ $field ] !== $old_comment[ $field ] ) {
107
				$changes[ $field ] = array( $new_comment[ $field ], $old_comment[ $field ] );
108
			}
109
		}
110
111
		if ( ! empty( $changes ) ) {
112
			/**
113
			 * Signals to the sync listener that this comment's contents were modified and a sync action
114
			 * reflecting the change(s) to the content should be sent
115
			 *
116
			 * @since 4.9.0
117
			 *
118
			 * @param int $new_comment['comment_ID'] ID of comment whose content was modified
119
			 * @param mixed $changes Array of changed comment fields with before and after values
120
			 */
121
			do_action( 'jetpack_modified_comment_contents', $new_comment['comment_ID'], $changes );
122
		}
123
		return $new_comment;
124
	}
125
126
	/**
127
	 * Initialize comments action listeners for full sync.
128
	 *
129
	 * @access public
130
	 *
131
	 * @param callable $callable Action handler callable.
132
	 */
133
	public function init_full_sync_listeners( $callable ) {
134
		add_action( 'jetpack_full_sync_comments', $callable ); // Also send comments meta.
135
	}
136
137
	/**
138
	 * Gets a filtered list of comment types that sync can hook into.
139
	 *
140
	 * @access public
141
	 *
142
	 * @return array Defaults to [ '', 'trackback', 'pingback' ].
143
	 */
144
	public function get_whitelisted_comment_types() {
145
		/**
146
		 * Comment types present in this list will sync their status changes to WordPress.com.
147
		 *
148
		 * @since 7.6.0
149
		 *
150
		 * @param array A list of comment types.
151
		 */
152
		return apply_filters(
153
			'jetpack_sync_whitelisted_comment_types',
154
			array( '', 'trackback', 'pingback' )
155
		);
156
	}
157
158
	/**
159
	 * Initialize the module in the sender.
160
	 *
161
	 * @access public
162
	 */
163
	public function init_before_send() {
164
		add_filter( 'jetpack_sync_before_send_wp_insert_comment', array( $this, 'expand_wp_insert_comment' ) );
165
166
		foreach ( $this->get_whitelisted_comment_types() as $comment_type ) {
167
			foreach ( array( 'unapproved', 'approved' ) as $comment_status ) {
168
				$comment_action_name = "comment_{$comment_status}_{$comment_type}";
169
				add_filter(
170
					'jetpack_sync_before_send_' . $comment_action_name,
171
					array(
172
						$this,
173
						'expand_wp_insert_comment',
174
					)
175
				);
176
			}
177
		}
178
179
		// Full sync.
180
		add_filter( 'jetpack_sync_before_send_jetpack_full_sync_comments', array( $this, 'expand_comment_ids' ) );
181
	}
182
183
	/**
184
	 * Enqueue the comments actions for full sync.
185
	 *
186
	 * @access public
187
	 *
188
	 * @param array   $config               Full sync configuration for this sync module.
189
	 * @param int     $max_items_to_enqueue Maximum number of items to enqueue.
190
	 * @param boolean $state                True if full sync has finished enqueueing this module, false otherwise.
191
	 * @return array Number of actions enqueued, and next module state.
192
	 */
193
	public function enqueue_full_sync_actions( $config, $max_items_to_enqueue, $state ) {
194
		global $wpdb;
195
		return $this->enqueue_all_ids_as_action( 'jetpack_full_sync_comments', $wpdb->comments, 'comment_ID', $this->get_where_sql( $config ), $max_items_to_enqueue, $state );
196
	}
197
198
	/**
199
	 * Retrieve an estimated number of actions that will be enqueued.
200
	 *
201
	 * @access public
202
	 *
203
	 * @param array $config Full sync configuration for this sync module.
204
	 * @return int Number of items yet to be enqueued.
205
	 */
206 View Code Duplication
	public function estimate_full_sync_actions( $config ) {
207
		global $wpdb;
208
209
		$query = "SELECT count(*) FROM $wpdb->comments";
210
211
		$where_sql = $this->get_where_sql( $config );
212
		if ( $where_sql ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $where_sql of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
213
			$query .= ' WHERE ' . $where_sql;
214
		}
215
216
		// TODO: Call $wpdb->prepare on the following query.
217
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
218
		$count = $wpdb->get_var( $query );
219
220
		return (int) ceil( $count / self::ARRAY_CHUNK_SIZE );
221
	}
222
223
	/**
224
	 * Retrieve the WHERE SQL clause based on the module config.
225
	 *
226
	 * @access private
227
	 *
228
	 * @param array $config Full sync configuration for this sync module.
229
	 * @return string WHERE SQL clause, or `null` if no comments are specified in the module config.
230
	 */
231
	private function get_where_sql( $config ) {
232
		if ( is_array( $config ) ) {
233
			return 'comment_ID IN (' . implode( ',', array_map( 'intval', $config ) ) . ')';
234
		}
235
236
		return null;
237
	}
238
239
	/**
240
	 * Retrieve the actions that will be sent for this module during a full sync.
241
	 *
242
	 * @access public
243
	 *
244
	 * @return array Full sync actions of this module.
245
	 */
246
	public function get_full_sync_actions() {
247
		return array( 'jetpack_full_sync_comments' );
248
	}
249
250
	/**
251
	 * Count all the actions that are going to be sent.
252
	 *
253
	 * @access public
254
	 *
255
	 * @param array $action_names Names of all the actions that will be sent.
256
	 * @return int Number of actions.
257
	 */
258
	public function count_full_sync_actions( $action_names ) {
259
		return $this->count_actions( $action_names, array( 'jetpack_full_sync_comments' ) );
260
	}
261
262
	/**
263
	 * Expand the comment status change before the data is serialized and sent to the server.
264
	 *
265
	 * @access public
266
	 * @todo This is not used currently - let's implement it.
267
	 *
268
	 * @param array $args The hook parameters.
269
	 * @return array The expanded hook parameters.
270
	 */
271
	public function expand_wp_comment_status_change( $args ) {
272
		return array( $args[0], $this->filter_comment( $args[1] ) );
273
	}
274
275
	/**
276
	 * Expand the comment creation before the data is serialized and sent to the server.
277
	 *
278
	 * @access public
279
	 *
280
	 * @param array $args The hook parameters.
281
	 * @return array The expanded hook parameters.
282
	 */
283
	public function expand_wp_insert_comment( $args ) {
284
		return array( $args[0], $this->filter_comment( $args[1] ) );
285
	}
286
287
	/**
288
	 * Filter a comment object to the fields we need.
289
	 *
290
	 * @access public
291
	 *
292
	 * @param \WP_Comment $comment The unfiltered comment object.
293
	 * @return \WP_Comment Filtered comment object.
294
	 */
295
	public function filter_comment( $comment ) {
296
		/**
297
		 * Filters whether to prevent sending comment data to .com
298
		 *
299
		 * Passing true to the filter will prevent the comment data from being sent
300
		 * to the WordPress.com.
301
		 * Instead we pass data that will still enable us to do a checksum against the
302
		 * Jetpacks data but will prevent us from displaying the data on in the API as well as
303
		 * other services.
304
		 *
305
		 * @since 4.2.0
306
		 *
307
		 * @param boolean false prevent post data from bing synced to WordPress.com
308
		 * @param mixed $comment WP_COMMENT object
309
		 */
310
		if ( apply_filters( 'jetpack_sync_prevent_sending_comment_data', false, $comment ) ) {
311
			$blocked_comment                   = new \stdClass();
312
			$blocked_comment->comment_ID       = $comment->comment_ID;
313
			$blocked_comment->comment_date     = $comment->comment_date;
314
			$blocked_comment->comment_date_gmt = $comment->comment_date_gmt;
315
			$blocked_comment->comment_approved = 'jetpack_sync_blocked';
316
			return $blocked_comment;
317
		}
318
319
		return $comment;
320
	}
321
322
	/**
323
	 * Whether a certain comment meta key is whitelisted for sync.
324
	 *
325
	 * @access public
326
	 *
327
	 * @param string $meta_key Comment meta key.
328
	 * @return boolean Whether the meta key is whitelisted.
329
	 */
330
	public function is_whitelisted_comment_meta( $meta_key ) {
331
		return in_array( $meta_key, Settings::get_setting( 'comment_meta_whitelist' ), true );
332
	}
333
334
	/**
335
	 * Handler for filtering out non-whitelisted comment meta.
336
	 *
337
	 * @access public
338
	 *
339
	 * @param array $args Hook args.
340
	 * @return array|boolean False if not whitelisted, the original hook args otherwise.
341
	 */
342
	public function filter_meta( $args ) {
343
		return ( $this->is_whitelisted_comment_meta( $args[2] ) ? $args : false );
344
	}
345
346
	/**
347
	 * Expand the comment IDs to comment objects and meta before being serialized and sent to the server.
348
	 *
349
	 * @access public
350
	 *
351
	 * @param array $args The hook parameters.
352
	 * @return array The expanded hook parameters.
353
	 */
354
	public function expand_comment_ids( $args ) {
355
		list( $comment_ids, $previous_interval_end ) = $args;
356
		$comments                                    = get_comments(
357
			array(
358
				'include_unapproved' => true,
359
				'comment__in'        => $comment_ids,
360
				'orderby'            => 'comment_ID',
361
				'order'              => 'DESC',
362
			)
363
		);
364
365
		return array(
366
			$comments,
367
			$this->get_metadata( $comment_ids, 'comment', Settings::get_setting( 'comment_meta_whitelist' ) ),
368
			$previous_interval_end,
369
		);
370
	}
371
}
372