Completed
Push — master ( ed64c2...186a7a )
by
unknown
8s
created

Helper   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 252
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 3
Bugs 1 Features 1
Metric Value
c 3
b 1
f 1
dl 0
loc 252
rs 8.3206
wmc 51
lcom 0
cbo 1

5 Methods

Rating   Name   Duplication   Size   Complexity  
B trim_words() 0 36 6
B close_tags() 0 33 4
F paginate_links() 0 96 27
A array_to_object() 0 15 4
D get_archives_title() 0 29 10

How to fix   Complexity   

Complex Class

Complex classes like Helper 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 Helper, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Includes multiple helper function.
4
 *
5
 * @package Classy
6
 */
7
8
namespace Classy;
9
10
/**
11
 * Class Helper.
12
 */
13
class Helper {
14
15
	/**
16
	 * Trims text to a certain number of words.
17
	 *
18
	 * @param string $text         Text to trim.
19
	 * @param int    $num_words    Number of words. Default 55.
20
	 * @param string $more         Optional. What to append if $text needs to be trimmed. Default '&hellip;'.
21
	 * @param string $allowed_tags Html allowed tags.
22
	 *
23
	 * @return string Trimmed text.
24
	 */
25
	public static function trim_words( $text, $num_words = 55, $more = null, $allowed_tags = 'p a span b i br blockquote' ) {
26
		if ( null === $more ) {
27
			$more = __( '&hellip;' );
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $more. This often makes code more readable.
Loading history...
28
		}
29
30
		$original_text = $text;
31
		$allowed_tag_string = '';
32
33
		foreach ( explode( ' ', $allowed_tags ) as $tag ) {
34
			$allowed_tag_string .= '<' . $tag . '>';
35
		}
36
37
		$text = strip_tags( $text, $allowed_tag_string );
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $text. This often makes code more readable.
Loading history...
38
39
		if ( 'characters' === _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
40
			$text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $text. This often makes code more readable.
Loading history...
41
			preg_match_all( '/./u', $text, $words_array );
42
			$words_array = array_slice( $words_array[0], 0, $num_words + 1 );
43
			$sep = '';
44
		} else {
45
			$words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
46
			$sep = ' ';
47
		}
48
49
		if ( count( $words_array ) > $num_words ) {
50
			array_pop( $words_array );
51
			$text = implode( $sep, $words_array );
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $text. This often makes code more readable.
Loading history...
52
			$text = $text . $more;
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $text. This often makes code more readable.
Loading history...
53
		} else {
54
			$text = implode( $sep, $words_array );
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $text. This often makes code more readable.
Loading history...
55
		}
56
57
		$text = self::close_tags( $text );
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $text. This often makes code more readable.
Loading history...
58
59
		return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
60
	}
61
62
	/**
63
	 * Close tags in html code.
64
	 *
65
	 * @param string $html Html code to be checked.
66
	 *
67
	 * @return string
68
	 */
69
	public static function close_tags( $html ) {
70
		// Put all opened tags into an array.
71
		preg_match_all( '#<([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result );
72
73
		$openedtags = $result[1];
74
75
		// Put all closed tags into an array.
76
		preg_match_all( '#</([a-z]+)>#iU', $html, $result );
77
78
		$closedtags = $result[1];
79
		$len_opened = count( $openedtags );
80
81
		// All tags are closed.
82
		if ( count( $closedtags ) === $len_opened ) {
83
			return $html;
84
		}
85
86
		$openedtags = array_reverse( $openedtags );
87
88
		// Close tags.
89
		for ( $i = 0; $i < $len_opened; $i++ ) {
90
			if ( ! in_array( $openedtags[ $i ], $closedtags, true ) ) {
91
				$html .= '</' . $openedtags[ $i ] . '>';
92
			} else {
93
				unset( $closedtags[ array_search( $openedtags[ $i ], $closedtags ) ] );
94
			}
95
		}
96
97
		$html = str_replace( array( '</br>', '</hr>', '</wbr>' ), '', $html );
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $html. This often makes code more readable.
Loading history...
98
		$html = str_replace( array( '<br>', '<hr>', '<wbr>' ), array( '<br />', '<hr />', '<wbr />' ), $html );
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $html. This often makes code more readable.
Loading history...
99
100
		return $html;
101
	}
102
103
	/**
104
	 * Retrieve paginated link for archive post pages.
105
	 *
106
	 * @param string|array $args Optional. Array or string of arguments for generating paginated links for archives.
107
	 *
108
	 * @return array
109
	 */
110
	public static function paginate_links( $args = '' ) {
111
		$defaults = array(
112
			'base' => '%_%', // Example http://example.com/all_posts.php%_% : %_% is replaced by format (below).
113
			'format' => '?page=%#%', // Example ?page=%#% : %#% is replaced by the page number.
114
			'total' => 1,
115
			'current' => 0,
116
			'show_all' => false,
117
			'prev_next' => true,
118
			'prev_text' => __( '&laquo; Previous' ),
119
			'next_text' => __( 'Next &raquo;' ),
120
			'end_size' => 1,
121
			'mid_size' => 2,
122
			'type' => 'array',
123
			'add_args' => false, // Array of query args to add.
124
			'add_fragment' => '',
125
		);
126
		$args = wp_parse_args( $args, $defaults );
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $args. This often makes code more readable.
Loading history...
127
128
		// Who knows what else people pass in $args.
129
		$args['total'] = intval( (int) $args['total'] );
130
		if ( $args['total'] < 2 ) {
131
			return array();
132
		}
133
		$args['current'] = (int) $args['current'];
134
		$args['end_size'] = 0 < (int) $args['end_size'] ? (int) $args['end_size'] : 1; // Out of bounds?  Make it the default.
135
		$args['mid_size'] = 0 <= (int) $args['mid_size'] ? (int) $args['mid_size'] : 2;
136
		$args['add_args'] = is_array( $args['add_args'] ) ? $args['add_args'] : false;
137
		$page_links = array();
138
		$dots = false;
139
		if ( $args['prev_next'] && $args['current'] && 1 < $args['current'] ) {
140
			$link = str_replace( '%_%', 2 === absint( $args['current'] ) ? '' : $args['format'], $args['base'] );
141
			$link = str_replace( '%#%', $args['current'] - 1, $link );
142
			if ( $args['add_args'] ) {
143
				$link = add_query_arg( $args['add_args'], $link );
144
			}
145
			$link .= $args['add_fragment'];
146
			$link = untrailingslashit( $link );
147
			$page_links[] = array(
148
				'class' => 'prev page-numbers',
149
				'link' => esc_url( apply_filters( 'paginate_links', $link ) ),
150
				'title' => $args['prev_text'],
151
			);
152
		}
153
		for ( $n = 1; $n <= $args['total']; $n++ ) {
154
			$n_display = number_format_i18n( $n );
155
			if ( absint( $args['current'] ) === $n ) {
156
				$page_links[] = array(
157
					'class' => 'page-number page-numbers current',
158
					'title' => $n_display,
159
					'text' => $n_display,
160
					'name' => $n_display,
161
					'current' => true,
162
				);
163
				$dots = true;
164
			} else {
165
				if ( $args['show_all'] || ( $n <= $args['end_size'] || ( $args['current'] && $n >= $args['current'] - $args['mid_size'] && $n <= $args['current'] + $args['mid_size'] ) || $n > $args['total'] - $args['end_size'] ) ) {
166
					$link = str_replace( '%_%', 1 === absint( $n ) ? '' : $args['format'], $args['base'] );
167
					$link = str_replace( '%#%', $n, $link );
168
					$link = trailingslashit( $link ) . ltrim( $args['add_fragment'], '/' );
169
					if ( $args['add_args'] ) {
170
						$link = rtrim( add_query_arg( $args['add_args'], $link ), '/' );
171
					}
172
					$link = str_replace( ' ', '+', $link );
173
					$link = untrailingslashit( $link );
174
					$page_links[] = array(
175
						'class' => 'page-number page-numbers',
176
						'link' => esc_url( apply_filters( 'paginate_links', $link ) ),
177
						'title' => $n_display,
178
						'name' => $n_display,
179
						'current' => absint( $args['current'] ) === $n,
180
					);
181
					$dots = true;
182
				} elseif ( $dots && ! $args['show_all'] ) {
183
					$page_links[] = array(
184
						'class' => 'dots',
185
						'title' => __( '&hellip;' ),
186
					);
187
					$dots = false;
188
				}
189
			}
190
		}
191
		if ( $args['prev_next'] && $args['current'] && ( $args['current'] < $args['total'] || -1 === intval( $args['total'] ) ) ) {
192
			$link = str_replace( '%_%', $args['format'], $args['base'] );
193
			$link = str_replace( '%#%', $args['current'] + 1, $link );
194
			if ( $args['add_args'] ) {
195
				$link = add_query_arg( $args['add_args'], $link );
196
			}
197
			$link = untrailingslashit( trailingslashit( $link ) . $args['add_fragment'] );
198
			$page_links[] = array(
199
				'class' => 'next page-numbers',
200
				'link' => esc_url( apply_filters( 'paginate_links', $link ) ),
201
				'title' => $args['next_text'],
202
			);
203
		}
204
		return $page_links;
205
	}
206
207
	/**
208
	 * Converts array to object recursively.
209
	 *
210
	 * @param array $array Array to be converted.
211
	 *
212
	 * @return object
213
	 */
214
	public static function array_to_object( $array ) {
215
		$obj = new \stdClass;
216
217
		foreach ( $array as $k => $v ) {
218
			if ( strlen( $k ) ) {
219
				if ( is_array( $v ) ) {
220
					$obj->{$k} = self::array_to_object( $v ); // Recursion.
221
				} else {
222
					$obj->{$k} = $v;
223
				}
224
			}
225
		}
226
227
		return $obj;
228
	}
229
230
	/**
231
	 * Returns Current Archives Page Title.
232
	 *
233
	 * @return string
234
	 */
235
	public static function get_archives_title() {
236
		$textdomain = Classy::textdomain();
237
		$archives_title = 'Archives';
238
239
	    if ( is_category() ) {
240
	        $archives_title = single_cat_title( '', false );
241
	    } else if ( is_tag() ) {
242
	        $archives_title = 'Tag: ' . single_tag_title( '', false );
243
	    } else if ( is_author() ) {
244
	        if ( have_posts() ) {
245
	            the_post();
246
	            $archives_title = 'Author: ' . get_the_author();
247
	        }
248
249
	        rewind_posts();
250
	    } else if ( is_search() ) {
251
	        $archives_title = sprintf( __( 'Search Results for: %s', $textdomain ), '<span>' . get_search_query() . '</span>' );
252
	    } else if ( is_archive() ) {
253
	        if ( is_day() ) {
254
	            $archives_title = get_the_date();
255
	        } elseif ( is_month() ) {
256
	            $archives_title = get_the_date( _x( 'F Y', 'monthly archives date format', $textdomain ) );
257
	        } elseif ( is_year() ) {
258
	            $archives_title = get_the_date( _x( 'Y', 'yearly archives date format', $textdomain ) );
259
	        }
260
		}
261
262
	    return $archives_title;
263
	}
264
}
265