MonsterInsights_Site_Notes_DB_Base::get_items()   F
last analyzed

Complexity

Conditions 22
Paths 5760

Size

Total Lines 104
Code Lines 72

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 22
eloc 72
c 1
b 0
f 0
nc 5760
nop 2
dl 0
loc 104
rs 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
 * This file contains the class to interact with database.
5
 *
6
 * @since 1.0.0
7
 *
8
 * @package MonsterInsights
9
 * @package MonsterInsights_Site_Notes
10
 */
11
12
/**
13
 * Class containing CRUD operations for site notes in the custom post type.
14
 *
15
 * @since 1.0.0
16
 */
17
class MonsterInsights_Site_Notes_DB_Base
18
{
19
20
	private function create_post_type()
21
	{
22
		$args = array(
23
			'public'             => false,
24
			'publicly_queryable' => false,
25
			'show_ui'            => false,
26
			'show_in_menu'       => false,
27
			'query_var'          => true,
28
			'capability_type'    => 'post',
29
			'has_archive'        => false,
30
			'supports'           => array('title', 'author', 'custom-fields')
31
		);
32
33
		register_post_type('monsterinsights_note', $args);
34
	}
35
36
	private function create_taxonomy()
37
	{
38
		$args = array(
39
			'hierarchical' => false,
40
			'show_ui'      => false,
41
			'query_var'    => true,
42
			'public'       => false,
43
		);
44
45
		register_taxonomy('monsterinsights_note_category', array('monsterinsights_note'), $args);
46
	}
47
48
	public function insert_default_categories()
49
	{
50
		if (get_option('monsterinsights_sitenotes_installed')) {
51
			return;
52
		}
53
54
		$categories = array(
55
			__('Website Updates', 'google-analytics-for-wordpress'),
56
			__('Blog Post', 'google-analytics-for-wordpress'),
57
			__('Promotion', 'google-analytics-for-wordpress'),
58
		);
59
60
		foreach ($categories as $category) {
61
			$this->create_category(
62
				array(
63
					'name' => $category,
64
				)
65
			);
66
		}
67
68
		update_option('monsterinsights_sitenotes_installed', time());
69
	}
70
71
	public function install()
72
	{
73
		$this->create_post_type();
74
		$this->create_taxonomy();
75
	}
76
77
	private function get_category_name($id)
78
	{
79
		$term = get_term($id, 'monsterinsights_note_category');
80
		if (is_wp_error($term)) {
81
			return false;
82
		}
83
84
		return $term->name;
0 ignored issues
show
Bug introduced by
The property name does not seem to exist on WP_Error.
Loading history...
85
	}
86
87
	/**
88
	 * Add new Site Note.
89
	 *
90
	 * @since 1.0.0
91
	 *
92
	 * @param array $data  Data to store.
93
	 *
94
	 * @return int|WP_Error
95
	 */
96
	public function create($data)
97
	{
98
		if (empty($data['note'])) {
99
			return new WP_Error(400, __('Your Site Note Cannot be Empty', 'google-analytics-for-wordpress'));
100
		}
101
102
		$note_post = array(
103
			'ID' => isset($data['id']) ? $data['id'] : null,
104
			'post_title'    => sanitize_text_field($data['note']),
105
			'post_status'   => 'publish',
106
			'post_author'   => isset( $data['author_id'] ) ? intval( $data['author_id'] ) : get_current_user_id(),
107
			'post_date'     => !empty($data['date']) ? $data['date'] : current_datetime()->format('Y-m-d'),
108
			'post_type'     => 'monsterinsights_note',
109
		);
110
		$post_id = wp_insert_post($note_post, true, false);
111
112
		if (is_wp_error($post_id)) {
113
			return $post_id;
114
		}
115
116
		// Attach the note to the category.
117
		if (!empty($data['category'])) {
118
			if ($category_name = $this->get_category_name($data['category'])) {
119
				wp_set_object_terms($post_id, $data['category'], 'monsterinsights_note_category');
0 ignored issues
show
Bug introduced by
It seems like $post_id can also be of type WP_Error; however, parameter $object_id of wp_set_object_terms() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

119
				wp_set_object_terms(/** @scrutinizer ignore-type */ $post_id, $data['category'], 'monsterinsights_note_category');
Loading history...
120
				update_post_meta($post_id, '_category', $category_name);
0 ignored issues
show
Bug introduced by
It seems like $post_id can also be of type WP_Error; however, parameter $post_id of update_post_meta() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

120
				update_post_meta(/** @scrutinizer ignore-type */ $post_id, '_category', $category_name);
Loading history...
121
			}
122
		} else {
123
			wp_set_object_terms($post_id, array(), 'monsterinsights_note_category');
124
			update_post_meta($post_id, '_category', '');
125
		}
126
127
		if (!empty($data['medias'])) {
128
			update_post_meta($post_id, 'medias', $data['medias']);
129
		}
130
131
		if (isset($data['important'])) {
132
			update_post_meta($post_id, 'important', $data['important']);
133
		}
134
135
		return $post_id;
136
	}
137
138
	/**
139
	 * Add new Site Note's category.
140
	 *
141
	 * @since 1.0.0
142
	 *
143
	 * @param array $data  Data to store.
144
	 *
145
	 * @return int|WP_Error
146
	 */
147
	public function create_category($data)
148
	{
149
		if (isset($data['id'])) {
150
			$created_term = wp_update_term($data['id'], 'monsterinsights_note_category', array('name' => $data['name']));
151
		} else {
152
			$created_term = wp_insert_term($data['name'], 'monsterinsights_note_category');
153
		}
154
155
		if (is_wp_error($created_term)) {
156
			return $created_term;
157
		}
158
159
		if (!empty($data['background_color'])) {
160
			update_term_meta($created_term['term_id'], 'background_color', $data['background_color']);
161
		}
162
163
		return $created_term['term_id'];
164
	}
165
166
	/**
167
	 * Get site note with ID
168
	 *
169
	 * @since 1.0.0
170
	 *
171
	 * @param int $post_id Single entry.
172
	 *
173
	 * @return array|WP_Error
174
	 */
175
	public function get($post_id)
176
	{
177
		$post = get_post($post_id);
178
179
		if (!$post) {
180
			return new WP_Error(400, __('Note not found', 'google-analytics-for-wordpress'));
181
		}
182
183
		$categories = wp_get_object_terms($post->ID, 'monsterinsights_note_category');
184
		$post_title = get_the_title($post);
0 ignored issues
show
Bug introduced by
It seems like $post can also be of type array; however, parameter $post of get_the_title() does only seem to accept WP_Post|integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

184
		$post_title = get_the_title(/** @scrutinizer ignore-type */ $post);
Loading history...
185
		$note = array(
186
			'id'  => $post->ID,
187
			'note_title' => wp_strip_all_tags(html_entity_decode(htmlspecialchars_decode($post_title), ENT_COMPAT, 'UTF-8')),
188
			'note_date' => get_the_date( 'Y-m-d', $post),
0 ignored issues
show
Bug introduced by
It seems like $post can also be of type array; however, parameter $post of get_the_date() does only seem to accept WP_Post|integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

188
			'note_date' => get_the_date( 'Y-m-d', /** @scrutinizer ignore-type */ $post),
Loading history...
189
			'note_date_ymd' => get_the_date( 'Y-m-d', $post ),
190
			'status' => get_post_status($post),
0 ignored issues
show
Bug introduced by
It seems like $post can also be of type array; however, parameter $post of get_post_status() does only seem to accept WP_Post|integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

190
			'status' => get_post_status(/** @scrutinizer ignore-type */ $post),
Loading history...
191
			'important' => (int) get_post_meta($post->ID, 'important', true),
192
			'medias' => array(),
193
			'category' => array(
194
				'id' => 0,
195
			),
196
		);
197
198
		if (
199
			monsterinsights_is_pro_version()
200
			&& $medias = get_post_meta( $post->ID, 'medias', true )
201
		) {
202
			if ( ! empty( $medias ) ) {
203
				foreach ($medias as $media_id) {
204
					$attachment_url = wp_get_attachment_url($media_id);
205
					if (!$attachment_url) {
206
						continue;
207
					}
208
209
					$attachment_filename = basename( get_attached_file( $media_id ) );
0 ignored issues
show
Bug introduced by
It seems like get_attached_file($media_id) can also be of type false; however, parameter $path of basename() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

209
					$attachment_filename = basename( /** @scrutinizer ignore-type */ get_attached_file( $media_id ) );
Loading history...
210
211
					$note['medias'][ $media_id ] = [
212
						'url'  => $attachment_url,
213
						'name' => $attachment_filename
214
					];
215
				}
216
			}
217
		}
218
219
		$note['medias'] = (object) $note['medias'];
220
221
		if ($post->post_author) {
222
			$user = get_userdata($post->post_author);
0 ignored issues
show
Bug introduced by
$post->post_author of type string is incompatible with the type integer expected by parameter $user_id of get_userdata(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

222
			$user = get_userdata(/** @scrutinizer ignore-type */ $post->post_author);
Loading history...
223
224
			if ($user) {
225
				$note['author'] = array(
226
					'id'   => $user->ID,
227
					'name' => $user->display_name,
228
				);
229
			}
230
		}
231
232
		if ($categories) {
0 ignored issues
show
introduced by
$categories is of type WP_Error, thus it always evaluated to true.
Loading history...
233
			$note['category'] = array(
234
				'id'   => $categories[0]->term_id,
235
				'name' => html_entity_decode( $categories[0]->name ),
236
			);
237
238
			if (monsterinsights_is_pro_version()) {
239
				$background_color = get_term_meta($categories[0]->term_id, 'background_color', true);
240
				$note['category']['background_color'] = !empty($background_color) ? $background_color : '#E9AF00';
241
			}
242
		}
243
244
		return $note;
245
	}
246
247
	/**
248
	 * Get rows from the database.
249
	 *
250
	 * @since 1.0.0
251
	 *
252
	 * @param array $args  Optional args.
253
	 * @param bool  $count Flag to return count instead of results.
254
	 *
255
	 * @return array|int
256
	 */
257
	public function get_items($args = array(), $count = false)
0 ignored issues
show
Unused Code introduced by
The parameter $count is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

257
	public function get_items($args = array(), /** @scrutinizer ignore-unused */ $count = false)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
258
	{
259
		$query_args = array(
260
			'post_type'      => 'monsterinsights_note',
261
			'posts_per_page' => $args['per_page'],
262
			'paged'          => $args['page'],
263
			'fields'         => 'ids',
264
			'orderby'        => $args['orderby'],
265
			'order'          => $args['order'],
266
			'post_status'    => (isset($args['filter']) && !empty($args['filter']['status']) && 'all' !== $args['filter']['status']) ? $args['filter']['status'] : ['publish'],
267
		);
268
269
		if (isset($args['search'])) {
270
			$query_args['s'] = $args['search'];
271
		}
272
273
		$all_notes_query_args = $query_args;
274
		$all_notes_query_args['post_status'] = ['publish'];
275
276
		if (isset($args['filter'])) {
277
			if (isset($args['filter']['important']) && !is_null($args['filter']['important'])) {
278
				$query_args['meta_key'] = 'important';
279
				$query_args['meta_value'] = $args['filter']['important'];
280
			}
281
			if (isset($args['filter']['category']) && !is_null($args['filter']['category'])) {
282
				$args['category'] = $args['filter']['category'];
283
			}
284
		}
285
286
		if (isset($args['filter']) && isset($args['filter']['date_range']) && !is_null($args['filter']['date_range'])) {
287
			$query_args['date_query'] = array(
288
				'after' => $args['filter']['date_range']['start'],
289
				'before' => $args['filter']['date_range']['end'],
290
				'inclusive' => true,
291
			);
292
			$all_notes_query_args['date_query'] = array(
293
				'after' => $args['filter']['date_range']['start'],
294
				'before' => $args['filter']['date_range']['end'],
295
				'inclusive' => true,
296
			);
297
		}
298
299
		if (!empty($args['category'])) {
300
			$query_args['tax_query'] = array(
301
				array(
302
					'taxonomy' => 'monsterinsights_note_category',
303
					'field'    => 'term_id',
304
					'terms'    => $args['category'],
305
				),
306
			);
307
		}
308
309
		if ('category' === $query_args['orderby']) {
310
			$query_args['meta_key'] = '_category';
311
			$query_args['orderby'] = 'meta_value';
312
		}
313
		// handle last30days
314
315
		if (isset($query_args['date_query']) && !is_null($query_args['date_query'])) {
316
			if ($query_args['date_query']['after'] == '' && $query_args['date_query']['before'] == '') {
317
				$query_args['date_query']['before'] = wp_date('Y-m-d', strtotime('-1 day'));
318
				$query_args['date_query']['after'] = wp_date('Y-m-d', strtotime('-30 days'));
319
				$all_notes_query_args['date_query']['before'] = wp_date('Y-m-d', strtotime('-1 day'));
320
				$all_notes_query_args['date_query']['after'] = wp_date('Y-m-d', strtotime('-30 days'));
321
			}
322
		}
323
324
		$items = array();
325
		$query = new WP_Query($query_args);
326
		$all_notes_query = new WP_Query($all_notes_query_args);
327
		$important_count = 0;
328
		if (!$query->have_posts()) {
329
			return array(
330
				'items' => $items,
331
				'pagination' => array(
332
					'total_published'    => $all_notes_query->post_count,
333
					'total_important'    => $important_count,
334
					'all_published'    => 0,
335
					'total'    => 0,
336
					'pages'    => 0,
337
					'page'     => $args['page'],
338
					'per_page' => $args['per_page'],
339
				),
340
			);
341
		}
342
343
		foreach ($query->posts as $post_id) {
344
			$post = $this->get($post_id);
345
			$is_important = get_post_meta($post_id, 'important', true);
346
			if($is_important){
347
				$important_count++;
348
			}
349
			$items[] = $post;
350
		}
351
352
		return array(
353
			'items' => $items,
354
			'pagination' => array(
355
				'total_published'    => $all_notes_query->post_count,
356
				'total_important'    => $important_count,
357
				'total'    => $query->found_posts,
358
				'pages'    => $query->max_num_pages,
359
				'page'     => $args['page'],
360
				'per_page' => $args['per_page'],
361
			),
362
		);
363
	}
364
365
	public function get_categories($args = array(), $count = false)
366
	{
367
		$query_args = array(
368
			'taxonomy' => 'monsterinsights_note_category',
369
			'hide_empty' => false,
370
		);
371
372
		if ($count) {
373
			return wp_count_terms($query_args);
374
		}
375
376
		$query_args['offset'] = ($args['page'] - 1) * $args['per_page'];
377
		$query_args['fields'] = 'id=>name';
378
		$query_args['order'] = $args['order'];
379
		$query_args['orderby'] = $args['orderby'];
380
381
		$items = get_terms($query_args);
382
		if (!$items) {
0 ignored issues
show
introduced by
$items is of type WP_Error, thus it always evaluated to true.
Loading history...
383
			return false;
384
		}
385
386
		$categories = array();
387
388
		foreach ($items as $term_id => $term_name) {
389
			$background_color = get_term_meta($term_id, 'background_color', true);
390
391
			$categories[] = array(
392
				'id' => $term_id,
393
				'name' => html_entity_decode( $term_name ),
394
				'background_color' => !empty($background_color) ? $background_color : '#E9AF00',
395
			);
396
		}
397
398
		return $categories;
399
	}
400
401
	/**
402
	 * Delete note by ID.
403
	 *
404
	 * @since 1.0.0
405
	 *
406
	 * @param int $note_id Note ID.
407
	 *
408
	 * @return WP_Post|false|null
409
	 */
410
	public function trash_note($note_id = 0)
411
	{
412
		if ( ! current_user_can( 'monsterinsights_save_settings' ) ) {
413
			return;
414
		}
415
416
		return wp_trash_post($note_id);
417
	}
418
419
	public function restore_note($note_id = 0)
420
	{
421
		if ( ! current_user_can( 'monsterinsights_save_settings' ) ) {
422
			return;
423
		}
424
		return wp_untrash_post($note_id);
425
	}
426
427
	public function delete_note($note_id = 0)
428
	{
429
		if ( ! current_user_can( 'monsterinsights_save_settings' ) ) {
430
			return;
431
		}
432
		return wp_delete_post($note_id, true);
433
	}
434
435
	public function delete_category($id = 0)
436
	{
437
		if ( ! current_user_can( 'monsterinsights_save_settings' ) ) {
438
			return;
439
		}
440
		return wp_delete_term($id, 'monsterinsights_note_category');
441
	}
442
}
443