Completed
Push — update/refactor-search-php ( f46b79...8d806f )
by
unknown
13:46 queued 06:54
created

Jetpack_Instant_Search   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 375
Duplicated Lines 9.6 %

Coupling/Cohesion

Components 2
Dependencies 6

Importance

Changes 0
Metric Value
dl 36
loc 375
rs 9.52
c 0
b 0
f 0
wmc 36
lcom 2
cbo 6

12 Methods

Rating   Name   Duplication   Size   Complexity  
A load_php() 0 9 2
A init_hooks() 16 16 2
A load_assets() 0 17 3
B inject_javascript_options() 0 68 5
A register_jetpack_instant_sidebar() 0 13 1
A print_instant_search_sidebar() 0 9 2
A load_and_initialize_tracks() 0 3 1
A get_asset_version() 0 5 3
A filter__posts_pre_query() 0 33 2
A action__parse_query() 0 25 4
C instant_api() 20 90 8
A get_search_aggregations_results() 0 7 3

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
 * Jetpack Search: Instant Front-End Search and Filtering
4
 *
5
 * @since 8.3.0
6
 * @package jetpack
7
 */
8
9
use Automattic\Jetpack\Connection\Client;
10
use Automattic\Jetpack\Constants;
11
12
class Jetpack_Instant_Search extends Jetpack_Search {
13
14
	/**
15
	 * Loads the php for this version of search
16
	 *
17
	 * @since 8.3.0
18
	 */
19
	public function load_php() {
20
		require_once dirname( __FILE__ ) . '/class.jetpack-search-template-tags.php';
21
		require_once JETPACK__PLUGIN_DIR . 'modules/widgets/search.php';
22
23
		if ( class_exists( 'WP_Customize_Manager' ) ) {
24
			require_once dirname( __FILE__ ) . '/class-jetpack-search-customize.php';
25
			new Jetpack_Search_Customize();
26
		}
27
	}
28
29
	/**
30
	 * Setup the various hooks needed for the plugin to take over search duties.
31
	 *
32
	 * @since 5.0.0
33
	 */
34 View Code Duplication
	public function init_hooks() {
35
		if ( ! is_admin() ) {
36
			add_filter( 'posts_pre_query', array( $this, 'filter__posts_pre_query' ), 10, 2 );
37
			add_action( 'parse_query', array( $this, 'action__parse_query' ), 10, 1 );
38
39
			add_action( 'init', array( $this, 'set_filters_from_widgets' ) );
40
41
			add_action( 'wp_enqueue_scripts', array( $this, 'load_assets' ) );
42
			add_action( 'wp_footer', array( $this, 'print_instant_search_sidebar' ) );
43
		} else {
44
			add_action( 'update_option', array( $this, 'track_widget_updates' ), 10, 3 );
45
		}
46
47
		add_action( 'widgets_init', array( $this, 'register_jetpack_instant_sidebar' ) );
48
		add_action( 'jetpack_deactivate_module_search', array( $this, 'move_search_widgets_to_inactive' ) );
49
	}
50
51
	/**
52
	 * Loads assets for Jetpack Instant Search Prototype featuring Search As You Type experience.
53
	 */
54
	public function load_assets() {
55
		$script_relative_path = '_inc/build/instant-search/jp-search.bundle.js';
56
		$style_relative_path  = '_inc/build/instant-search/instant-search.min.css';
57
		if ( ! file_exists( JETPACK__PLUGIN_DIR . $script_relative_path ) || ! file_exists( JETPACK__PLUGIN_DIR . $style_relative_path ) ) {
58
			return;
59
		}
60
61
		$script_version = self::get_asset_version( $script_relative_path );
62
		$script_path    = plugins_url( $script_relative_path, JETPACK__PLUGIN_FILE );
63
		wp_enqueue_script( 'jetpack-instant-search', $script_path, array(), $script_version, true );
64
		$this->load_and_initialize_tracks();
65
		$this->inject_javascript_options();
66
67
		$style_version = self::get_asset_version( $style_relative_path );
68
		$style_path    = plugins_url( $style_relative_path, JETPACK__PLUGIN_FILE );
69
		wp_enqueue_style( 'jetpack-instant-search', $style_path, array(), $style_version );
70
	}
71
72
	/**
73
	 * Passes all options to the JS app.
74
	 */
75
	protected function inject_javascript_options() {
76
		$widget_options = Jetpack_Search_Helpers::get_widgets_from_option();
77
		if ( is_array( $widget_options ) ) {
78
			$widget_options = end( $widget_options );
79
		}
80
81
		$filters = Jetpack_Search_Helpers::get_filters_from_widgets();
82
		$widgets = array();
83
		foreach ( $filters as $key => $filter ) {
84
			if ( ! isset( $widgets[ $filter['widget_id'] ] ) ) {
85
				$widgets[ $filter['widget_id'] ]['filters']   = array();
86
				$widgets[ $filter['widget_id'] ]['widget_id'] = $filter['widget_id'];
87
			}
88
			$new_filter                                   = $filter;
89
			$new_filter['filter_id']                      = $key;
90
			$widgets[ $filter['widget_id'] ]['filters'][] = $new_filter;
91
		}
92
93
		$post_type_objs   = get_post_types( array(), 'objects' );
94
		$post_type_labels = array();
95
		foreach ( $post_type_objs as $key => $obj ) {
96
			$post_type_labels[ $key ] = array(
97
				'singular_name' => $obj->labels->singular_name,
98
				'name'          => $obj->labels->name,
99
			);
100
		}
101
102
		$prefix  = Jetpack_Search_Options::OPTION_PREFIX;
103
		$options = array(
104
			// overlay options.
105
			'closeColor'      => (bool) get_option( $prefix . 'close_color', '#BD3854' ),
106
			'colorTheme'      => (bool) get_option( $prefix . 'color_theme', 'light' ),
107
			'enableInfScroll' => (bool) get_option( $prefix . 'inf_scroll', true ),
108
			'highlightColor'  => (bool) get_option( $prefix . 'highlight_color', '#FFC' ),
109
			'opacity'         => (bool) get_option( $prefix . 'opacity', 97 ),
110
			'showLogo'        => (bool) get_option( $prefix . 'show_logo', true ),
111
			'showPoweredBy'   => (bool) get_option( $prefix . 'show_powered_by', true ),
112
113
			// core config.
114
			'homeUrl'         => home_url(),
115
			'locale'          => str_replace( '_', '-', get_locale() ),
116
			'postsPerPage'    => get_option( 'posts_per_page' ),
117
			'siteId'          => Jetpack::get_option( 'id' ),
118
119
			// filtering.
120
			'postTypeFilters' => $widget_options['post_types'],
121
			'postTypes'       => $post_type_labels,
122
			'sort'            => $widget_options['sort'],
123
			'widgets'         => array_values( $widgets ),
124
		);
125
126
		/**
127
		 * Customize Instant Search Options.
128
		 *
129
		 * @module search
130
		 *
131
		 * @since 7.7.0
132
		 *
133
		 * @param array $options Array of parameters used in Instant Search queries.
134
		 */
135
		$options = apply_filters( 'jetpack_instant_search_options', $options );
136
137
		wp_localize_script(
138
			'jetpack-instant-search',
139
			'JetpackInstantSearchOptions',
140
			$options
141
		);
142
	}
143
144
	/**
145
	 * Registers a widget sidebar for Instant Search.
146
	 */
147
	public function register_jetpack_instant_sidebar() {
148
		$args = array(
149
			'name'          => 'Jetpack Search Sidebar',
150
			'id'            => 'jetpack-instant-search-sidebar',
151
			'description'   => 'Customize the sidebar inside the Jetpack Search overlay',
152
			'class'         => '',
153
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
154
			'after_widget'  => '</div>',
155
			'before_title'  => '<h2 class="widgettitle">',
156
			'after_title'   => '</h2>',
157
		);
158
		register_sidebar( $args );
159
	}
160
161
	/**
162
	 * Prints Instant Search sidebar.
163
	 */
164
	public function print_instant_search_sidebar() {
165
		?>
166
		<div class="jetpack-instant-search__widget-area" style="display: none">
167
			<?php if ( is_active_sidebar( 'jetpack-instant-search-sidebar' ) ) { ?>
168
				<?php dynamic_sidebar( 'jetpack-instant-search-sidebar' ); ?>
169
			<?php } ?>
170
		</div>
171
		<?php
172
	}
173
174
	/**
175
	 * Loads scripts for Tracks analytics library
176
	 */
177
	public function load_and_initialize_tracks() {
178
		wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
179
	}
180
181
	/**
182
	 * Get the version number to use when loading the file. Allows us to bypass cache when developing.
183
	 *
184
	 * @param string $file Path of the file we are looking for.
185
	 * @return string $script_version Version number.
186
	 */
187
	public static function get_asset_version( $file ) {
188
		return Jetpack::is_development_version() && file_exists( JETPACK__PLUGIN_DIR . $file )
189
			? filemtime( JETPACK__PLUGIN_DIR . $file )
190
			: JETPACK__VERSION;
191
	}
192
193
	/**
194
	 * Bypass the normal Search query since we will run it with instant search.
195
	 *
196
	 * @since 8.3.0
197
	 *
198
	 * @param array    $posts Current array of posts (still pre-query).
199
	 * @param WP_Query $query The WP_Query being filtered.
200
	 *
201
	 * @return array Array of matching posts.
202
	 */
203
	public function filter__posts_pre_query( $posts, $query ) {
204
		if ( ! $this->should_handle_query( $query ) ) {
205
			// Intentionally not adding the 'jetpack_search_abort' action since this should fire for every request except for search.
206
			return $posts;
207
		}
208
209
		/**
210
		 * Bypass the main query and return dummy data
211
		 *  WP Core doesn't call the set_found_posts and its filters when filtering
212
		 *  posts_pre_query like we do, so need to do these manually.
213
		 */
214
		$query->found_posts   = 1;
215
		$query->max_num_pages = 1;
216
217
		return array(
218
			new WP_Post(
219
				array(
220
					'ID'             => 1,
221
					'post_author'    => 1,
222
					'post_date'      => current_time( 'mysql' ),
223
					'post_date_gmt'  => current_time( 'mysql', 1 ),
224
					'post_title'     => 'Some title or other',
225
					'post_content'   => 'Whatever you want here. Maybe some cat pictures....',
226
					'post_status'    => 'publish',
227
					'comment_status' => 'closed',
228
					'ping_status'    => 'closed',
229
					'post_name'      => 'fake-page',
230
					'post_type'      => 'page',
231
					'filter'         => 'raw',
232
				)
233
			),
234
		);
235
	}
236
237
	/**
238
	 * Run the aggregations API query for any filtering
239
	 *
240
	 * @since 8.3.0
241
	 *
242
	 * @param WP_Query $query The WP_Query being filtered.
243
	 */
244
	public function action__parse_query( $query ) {
245
		if ( ! empty( $this->search_result ) ) {
246
			return;
247
		}
248
249
		if ( is_admin() ) {
250
			return;
251
		}
252
253
		if ( empty( $this->aggregations ) ) {
254
			return;
255
		}
256
257
		jetpack_require_lib( 'jetpack-wpes-query-builder/jetpack-wpes-query-builder' );
258
259
		$builder = new Jetpack_WPES_Query_Builder();
260
		$this->add_aggregations_to_es_query_builder( $this->aggregations, $builder );
261
		$this->search_result = $this->instant_api(
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->instant_api(array...ze' => 0, 'from' => 0)) of type object is incompatible with the declared type array of property $search_result.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
262
			array(
263
				'aggregations' => $builder->build_aggregation(),
264
				'size'         => 0,
265
				'from'         => 0,
266
			)
267
		);
268
	}
269
270
	/**
271
	 * Run an instant search on the WordPress.com public API.
272
	 *
273
	 * @since 8.3.0
274
	 *
275
	 * @param array $args Args conforming to the WP.com v1.3/sites/<blog_id>/search endpoint.
276
	 *
277
	 * @return object|WP_Error The response from the public API, or a WP_Error.
278
	 */
279
	public function instant_api( array $args ) {
280
		$start_time = microtime( true );
281
282
		// Cache locally to avoid remote request slowing the page.
283
		$transient_name = '_jetpack_instant_search_cache_' . md5( wp_json_encode( $args ) );
284
		$cache          = get_transient( $transient_name );
285
		if ( false !== $cache ) {
286
			$end_time = microtime( true );
0 ignored issues
show
Unused Code introduced by
$end_time is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
287
			return $cache;
288
		}
289
290
		$endpoint     = sprintf( '/sites/%s/search', $this->jetpack_blog_id );
291
		$query_params = urldecode( http_build_query( $args ) );
292
		$service_url  = 'https://public-api.wordpress.com/rest/v1.3' . $endpoint . '?' . $query_params;
293
294
		$request_args = array(
295
			'timeout'    => 10,
296
			'user-agent' => 'jetpack_search',
297
		);
298
299
		$request  = wp_remote_get( $service_url, $request_args );
300
		$end_time = microtime( true );
301
302
		if ( is_wp_error( $request ) ) {
303
			return $request;
304
		}
305
306
		$response_code = wp_remote_retrieve_response_code( $request );
307
		$response      = json_decode( wp_remote_retrieve_body( $request ), true );
308
309 View Code Duplication
		if ( ! $response_code || $response_code < 200 || $response_code >= 300 ) {
310
			/**
311
			 * Fires after a search query request has failed
312
			 *
313
			 * @module search
314
			 *
315
			 * @since  5.6.0
316
			 *
317
			 * @param array Array containing the response code and response from the failed search query
318
			 */
319
			do_action(
320
				'failed_jetpack_search_query',
321
				array(
322
					'response_code' => $response_code,
323
					'json'          => $response,
324
				)
325
			);
326
327
			return new WP_Error( 'invalid_search_api_response', 'Invalid response from API - ' . $response_code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_search_api_response'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
328
		}
329
330
		$took = is_array( $response ) && ! empty( $response['took'] )
331
			? $response['took']
332
			: null;
333
334
		$query = array(
335
			'args'          => $args,
336
			'response'      => $response,
337
			'response_code' => $response_code,
338
			'elapsed_time'  => ( $end_time - $start_time ) * 1000, // Convert from float seconds to ms.
339
			'es_time'       => $took,
340
			'url'           => $service_url,
341
		);
342
343
		/**
344
		 * Fires after a search request has been performed.
345
		 *
346
		 * Includes the following info in the $query parameter:
347
		 *
348
		 * array args Array of Elasticsearch arguments for the search
349
		 * array response Raw API response, JSON decoded
350
		 * int response_code HTTP response code of the request
351
		 * float elapsed_time Roundtrip time of the search request, in milliseconds
352
		 * float es_time Amount of time Elasticsearch spent running the request, in milliseconds
353
		 * string url API url that was queried
354
		 *
355
		 * @module search
356
		 *
357
		 * @since  5.0.0
358
		 * @since  5.8.0 This action now fires on all queries instead of just successful queries.
359
		 *
360
		 * @param array $query Array of information about the query performed
361
		 */
362
		do_action( 'did_jetpack_search_query', $query );
363
364
		// Update local cache.
365
		set_transient( $transient_name, $response, 1 * HOUR_IN_SECONDS );
366
367
		return $response;
368
	}
369
370
	/**
371
	 * Get the raw Aggregation results from the Elasticsearch response.
372
	 *
373
	 * @since  8.3.0
374
	 *
375
	 * @return array Array of Aggregations performed on the search.
376
	 */
377
	public function get_search_aggregations_results() {
378
		if ( empty( $this->search_result ) || ! isset( $this->search_result['aggregations'] ) ) {
379
			return array();
380
		}
381
382
		return $this->search_result['aggregations'];
383
	}
384
385
386
}
387