Completed
Push — try/gutenberg-separate-jetpack... ( e8dd3e...f0efb9 )
by Bernhard
39:26 queued 23:22
created

Jetpack_React_Page   B

Complexity

Total Complexity 51

Size/Duplication

Total Lines 321
Duplicated Lines 10.9 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
dl 35
loc 321
rs 7.92
c 0
b 0
f 0
wmc 51
lcom 1
cbo 5

14 Methods

Rating   Name   Duplication   Size   Complexity  
A get_page_hook() 0 6 1
B add_page_actions() 0 24 6
A jetpack_add_dashboard_sub_nav_item() 6 8 4
A jetpack_add_settings_sub_nav_item() 4 6 5
A add_fallback_head_meta() 0 3 1
A add_noscript_head_meta() 0 5 1
A add_legacy_browsers_head_script() 0 10 1
A jetpack_menu_order() 13 13 4
A render_nojs_configurable() 0 14 3
A page_render() 12 25 3
A get_dismissed_jetpack_notices() 0 12 1
A additional_styles() 0 6 2
F page_admin_scripts() 0 136 18
A get_flattened_settings() 0 5 1

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

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

1
<?php
2
include_once( 'class.jetpack-admin-page.php' );
3
4
// Builds the landing page and its menu
5
class Jetpack_React_Page extends Jetpack_Admin_Page {
6
7
	protected $dont_show_if_not_active = false;
8
9
	protected $is_redirecting = false;
10
11
	function get_page_hook() {
12
		$title = _x( 'Jetpack', 'The menu item label', 'jetpack' );
13
14
		// Add the main admin Jetpack menu
15
		return add_menu_page( 'Jetpack', $title, 'jetpack_admin_page', 'jetpack', array( $this, 'render' ), 'div' );
16
	}
17
18
	function add_page_actions( $hook ) {
19
		/** This action is documented in class.jetpack.php */
20
		do_action( 'jetpack_admin_menu', $hook );
21
22
		// Place the Jetpack menu item on top and others in the order they appear
23
		add_filter( 'custom_menu_order',         '__return_true' );
24
		add_filter( 'menu_order',                array( $this, 'jetpack_menu_order' ) );
25
26
		if ( ! isset( $_GET['page'] ) || 'jetpack' !== $_GET['page'] || ! empty( $_GET['configure'] ) ) {
27
			return; // No need to handle the fallback redirection if we are not on the Jetpack page
28
		}
29
30
		// Adding a redirect meta tag for older WordPress versions or if the REST API is disabled
31
		if ( $this->is_wp_version_too_old() || ! $this->is_rest_api_enabled() ) {
32
			$this->is_redirecting = true;
33
			add_action( 'admin_head', array( $this, 'add_fallback_head_meta' ) );
34
		}
35
36
		// Adding a redirect meta tag wrapped in noscript tags for all browsers in case they have JavaScript disabled
37
		add_action( 'admin_head', array( $this, 'add_noscript_head_meta' ) );
38
39
		// Adding a redirect tag wrapped in browser conditional comments
40
		add_action( 'admin_head', array( $this, 'add_legacy_browsers_head_script' ) );
41
	}
42
43
	/**
44
	 * Add Jetpack Dashboard sub-link and point it to AAG if the user can view stats, manage modules or if Protect is active.
45
	 *
46
	 * Works in Dev Mode or when user is connected.
47
	 *
48
	 * @since 4.3.0
49
	 */
50
	function jetpack_add_dashboard_sub_nav_item() {
51 View Code Duplication
		if ( Jetpack::is_development_mode() || Jetpack::is_active() ) {
52
			global $submenu;
53
			if ( current_user_can( 'jetpack_admin_page' ) ) {
54
				$submenu['jetpack'][] = array( __( 'Dashboard', 'jetpack' ), 'jetpack_admin_page', 'admin.php?page=jetpack#/dashboard' );
55
			}
56
		}
57
	}
58
59
	/**
60
	 * If user is allowed to see the Jetpack Admin, add Settings sub-link.
61
	 *
62
	 * @since 4.3.0
63
	 */
64
	function jetpack_add_settings_sub_nav_item() {
65 View Code Duplication
		if ( ( Jetpack::is_development_mode() || Jetpack::is_active() ) && current_user_can( 'jetpack_admin_page' ) && current_user_can( 'edit_posts' ) ) {
66
			global $submenu;
67
			$submenu['jetpack'][] = array( __( 'Settings', 'jetpack' ), 'jetpack_admin_page', 'admin.php?page=jetpack#/settings' );
68
		}
69
	}
70
71
	function add_fallback_head_meta() {
72
		echo '<meta http-equiv="refresh" content="0; url=?page=jetpack_modules">';
73
	}
74
75
	function add_noscript_head_meta() {
76
		echo '<noscript>';
77
		$this->add_fallback_head_meta();
78
		echo '</noscript>';
79
	}
80
81
	function add_legacy_browsers_head_script() {
82
		echo
83
			"<script type=\"text/javascript\">\n"
84
			. "/*@cc_on\n"
85
			. "if ( @_jscript_version <= 10) {\n"
86
			. "window.location.href = '?page=jetpack_modules';\n"
87
			. "}\n"
88
			. "@*/\n"
89
			. "</script>";
90
	}
91
92 View Code Duplication
	function jetpack_menu_order( $menu_order ) {
93
		$jp_menu_order = array();
94
95
		foreach ( $menu_order as $index => $item ) {
96
			if ( $item != 'jetpack' )
97
				$jp_menu_order[] = $item;
98
99
			if ( $index == 0 )
100
				$jp_menu_order[] = 'jetpack';
101
		}
102
103
		return $jp_menu_order;
104
	}
105
106
	// Render the configuration page for the module if it exists and an error
107
	// screen if the module is not configurable
108
	// @todo remove when real settings are in place
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
109
	function render_nojs_configurable( $module_name ) {
110
		$module_name = preg_replace( '/[^\da-z\-]+/', '', $_GET['configure'] );
111
112
		include_once( JETPACK__PLUGIN_DIR . '_inc/header.php' );
113
		echo '<div class="wrap configure-module">';
114
115
		if ( Jetpack::is_module( $module_name ) && current_user_can( 'jetpack_configure_modules' ) ) {
116
			Jetpack::admin_screen_configure_module( $module_name );
117
		} else {
118
			echo '<h2>' . esc_html__( 'Error, bad module.', 'jetpack' ) . '</h2>';
119
		}
120
121
		echo '</div><!-- /wrap -->';
122
	}
123
124
	function page_render() {
125
		// Handle redirects to configuration pages
126
		if ( ! empty( $_GET['configure'] ) ) {
127
			return $this->render_nojs_configurable( $_GET['configure'] );
128
		}
129
130
		/** This action is already documented in views/admin/admin-page.php */
131
		do_action( 'jetpack_notices' );
132
133
		// Try fetching by patch
134
		$static_html = @file_get_contents( JETPACK__PLUGIN_DIR . '_inc/build/static.html' );
135
136 View Code Duplication
		if ( false === $static_html ) {
137
138
			// If we still have nothing, display an error
139
			echo '<p>';
140
			esc_html_e( 'Error fetching static.html. Try running: ', 'jetpack' );
141
			echo '<code>yarn distclean && yarn build</code>';
142
			echo '</p>';
143
		} else {
144
145
			// We got the static.html so let's display it
146
			echo $static_html;
147
		}
148
	}
149
150
	/**
151
	 * Gets array of any Jetpack notices that have been dismissed.
152
	 *
153
	 * @since 4.0.1
154
	 * @return mixed|void
155
	 */
156
	function get_dismissed_jetpack_notices() {
157
		$jetpack_dismissed_notices = get_option( 'jetpack_dismissed_notices', array() );
158
		/**
159
		 * Array of notices that have been dismissed.
160
		 *
161
		 * @since 4.0.1
162
		 *
163
		 * @param array $jetpack_dismissed_notices If empty, will not show any Jetpack notices.
164
		 */
165
		$dismissed_notices = apply_filters( 'jetpack_dismissed_notices', $jetpack_dismissed_notices );
166
		return $dismissed_notices;
167
	}
168
169
	function additional_styles() {
170
		$rtl = is_rtl() ? '.rtl' : '';
171
172
		wp_enqueue_style( 'dops-css', plugins_url( "_inc/build/admin.dops-style$rtl.css", JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
173
		wp_enqueue_style( 'components-css', plugins_url( "_inc/build/style.min$rtl.css", JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
174
	}
175
176
	function page_admin_scripts() {
177
		if ( $this->is_redirecting ) {
178
			return; // No need for scripts on a fallback page
179
		}
180
181
		$is_dev_mode = Jetpack::is_development_mode();
182
183
		// Enqueue jp.js and localize it
184
		wp_enqueue_script( 'react-plugin', plugins_url( '_inc/build/admin.js', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION, true );
185
186
		if ( ! $is_dev_mode && Jetpack::is_active() ) {
187
			// Required for Analytics
188
			wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
189
		}
190
191
		// Collecting roles that can view site stats.
192
		$stats_roles = array();
193
		$enabled_roles = function_exists( 'stats_get_option' ) ? stats_get_option( 'roles' ) : array( 'administrator' );
194
195
		if ( ! function_exists( 'get_editable_roles' ) ) {
196
			require_once ABSPATH . 'wp-admin/includes/user.php';
197
		}
198
		foreach ( get_editable_roles() as $slug => $role ) {
199
			$stats_roles[ $slug ] = array(
200
				'name' => translate_user_role( $role['name'] ),
201
				'canView' => is_array( $enabled_roles ) ? in_array( $slug, $enabled_roles, true ) : false,
202
			);
203
		}
204
205
		// Load API endpoint base classes and endpoints for getting the module list fed into the JS Admin Page
206
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-xmlrpc-consumer-endpoint.php';
207
		require_once JETPACK__PLUGIN_DIR . '_inc/lib/core-api/class.jetpack-core-api-module-endpoints.php';
208
		$moduleListEndpoint = new Jetpack_Core_API_Module_List_Endpoint();
209
		$modules = $moduleListEndpoint->get_modules();
210
211
		// Preparing translated fields for JSON encoding by transforming all HTML entities to
212
		// respective characters.
213
		foreach( $modules as $slug => $data ) {
0 ignored issues
show
Bug introduced by
The expression $modules of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
214
			$modules[ $slug ]['name'] = html_entity_decode( $data['name'] );
215
			$modules[ $slug ]['description'] = html_entity_decode( $data['description'] );
216
			$modules[ $slug ]['short_description'] = html_entity_decode( $data['short_description'] );
217
			$modules[ $slug ]['long_description'] = html_entity_decode( $data['long_description'] );
218
		}
219
220
		// Get last post, to build the link to Customizer in the Related Posts module.
221
		$last_post = get_posts( array( 'posts_per_page' => 1 ) );
222
		$last_post = isset( $last_post[0] ) && $last_post[0] instanceof WP_Post
0 ignored issues
show
Bug introduced by
The class WP_Post does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
223
			? get_permalink( $last_post[0]->ID )
224
			: get_home_url();
225
226
		// Get information about current theme.
227
		$current_theme = wp_get_theme();
228
229
		// Get all themes that Infinite Scroll provides support for natively.
230
		$inf_scr_support_themes = array();
231
		foreach ( Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules/infinite-scroll/themes' ) as $path ) {
232
			if ( is_readable( $path ) ) {
233
				$inf_scr_support_themes[] = basename( $path, '.php' );
234
			}
235
		}
236
237
		// Add objects to be passed to the initial state of the app
238
		wp_localize_script( 'react-plugin', 'Initial_State', array(
239
			'WP_API_root' => esc_url_raw( rest_url() ),
240
			'WP_API_nonce' => wp_create_nonce( 'wp_rest' ),
241
			'pluginBaseUrl' => plugins_url( '', JETPACK__PLUGIN_FILE ),
242
			'connectionStatus' => array(
243
				'isActive'  => Jetpack::is_active(),
244
				'isStaging' => Jetpack::is_staging_site(),
245
				'devMode'   => array(
246
					'isActive' => $is_dev_mode,
247
					'constant' => defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG,
248
					'url'      => site_url() && false === strpos( site_url(), '.' ),
249
					'filter'   => apply_filters( 'jetpack_development_mode', false ),
250
				),
251
				'isPublic'	=> '1' == get_option( 'blog_public' ),
252
				'isInIdentityCrisis' => Jetpack::validate_sync_error_idc_option(),
253
			),
254
			'connectUrl' => Jetpack::init()->build_connect_url( true, false, false ),
255
			'dismissedNotices' => $this->get_dismissed_jetpack_notices(),
256
			'isDevVersion' => Jetpack::is_development_version(),
257
			'currentVersion' => JETPACK__VERSION,
258
			'getModules' => $modules,
259
			'showJumpstart' => jetpack_show_jumpstart(),
260
			'rawUrl' => Jetpack::build_raw_urls( get_home_url() ),
261
			'adminUrl' => esc_url( admin_url() ),
262
			'stats' => array(
263
				// data is populated asynchronously on page load
264
				'data'  => array(
265
					'general' => false,
266
					'day'     => false,
267
					'week'    => false,
268
					'month'   => false,
269
				),
270
				'roles' => $stats_roles,
271
			),
272
			'settings' => $this->get_flattened_settings( $modules ),
0 ignored issues
show
Bug introduced by
It seems like $modules defined by $moduleListEndpoint->get_modules() on line 209 can also be of type string; however, Jetpack_React_Page::get_flattened_settings() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
273
			'userData' => array(
274
//				'othersLinked' => Jetpack::get_other_linked_admins(),
275
				'currentUser'  => jetpack_current_user_data(),
276
			),
277
			'siteData' => array(
278
				'icon' => has_site_icon()
279
					? apply_filters( 'jetpack_photon_url', get_site_icon_url(), array( 'w' => 64 ) )
280
					: '',
281
				'siteVisibleToSearchEngines' => '1' == get_option( 'blog_public' ),
282
				/**
283
				 * Whether promotions are visible or not.
284
				 *
285
				 * @since 4.8.0
286
				 *
287
				 * @param bool $are_promotions_active Status of promotions visibility. True by default.
288
				 */
289
				'showPromotions' => apply_filters( 'jetpack_show_promotions', true ),
290
				'isAtomicSite' => jetpack_is_atomic_site(),
291
				'plan' => Jetpack::get_active_plan(),
292
			),
293
			'themeData' => array(
294
				'name'      => $current_theme->get( 'Name' ),
295
				'hasUpdate' => (bool) get_theme_update_available( $current_theme ),
296
				'support'   => array(
297
					'infinite-scroll' => current_theme_supports( 'infinite-scroll' ) || in_array( $current_theme->get_stylesheet(), $inf_scr_support_themes ),
298
				),
299
			),
300
			'locale' => Jetpack::get_i18n_data_json(),
301
			'localeSlug' => join( '-', explode( '_', jetpack_get_user_locale() ) ),
302
			'jetpackStateNotices' => array(
303
				'messageCode' => Jetpack::state( 'message' ),
304
				'errorCode' => Jetpack::state( 'error' ),
305
				'errorDescription' => Jetpack::state( 'error_description' ),
306
			),
307
			'tracksUserData' => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
308
			'currentIp' => function_exists( 'jetpack_protect_get_ip' ) ? jetpack_protect_get_ip() : false,
309
			'lastPostUrl' => esc_url( $last_post ),
310
		) );
311
	}
312
313
	/**
314
	 * Returns an array of modules and settings both as first class members of the object.
315
	 *
316
	 * @param array $modules the result of an API request to get all modules.
317
	 *
318
	 * @return array flattened settings with modules.
319
	 */
320
	function get_flattened_settings( $modules ) {
321
		$core_api_endpoint = new Jetpack_Core_API_Data();
322
		$settings = $core_api_endpoint->get_all_options();
323
		return $settings->data;
324
	}
325
}
326
327
/*
328
 * Only show Jump Start on first activation.
329
 * Any option 'jumpstart' other than 'new connection' will hide it.
330
 *
331
 * The option can be of 4 things, and will be stored as such:
332
 * new_connection      : Brand new connection - Show
333
 * jumpstart_activated : Jump Start has been activated - dismiss
334
 * jetpack_action_taken: Manual activation of a module already happened - dismiss
335
 * jumpstart_dismissed : Manual dismissal of Jump Start - dismiss
336
 *
337
 * @todo move to functions.global.php when available
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
338
 * @since 3.6
339
 * @return bool | show or hide
340
 */
341
function jetpack_show_jumpstart() {
342
	if ( ! Jetpack::is_active() ) {
343
		return false;
344
	}
345
	$jumpstart_option = Jetpack_Options::get_option( 'jumpstart' );
346
347
	$hide_options = array(
348
		'jumpstart_activated',
349
		'jetpack_action_taken',
350
		'jumpstart_dismissed'
351
	);
352
353
	if ( ! $jumpstart_option || in_array( $jumpstart_option, $hide_options ) ) {
354
		return false;
355
	}
356
357
	return true;
358
}
359
360
/**
361
 * Gather data about the current user.
362
 *
363
 * @since 4.1.0
364
 *
365
 * @return array
366
 */
367
function jetpack_current_user_data() {
368
	$current_user = wp_get_current_user();
369
	$is_master_user = $current_user->ID == Jetpack_Options::get_option( 'master_user' );
370
	$dotcom_data    = Jetpack::get_connected_user_data();
371
	// Add connected user gravatar to the returned dotcom_data.
372
	$dotcom_data['avatar'] = get_avatar_url( $dotcom_data['email'], array( 'size' => 64, 'default' => 'mysteryman' ) );
373
374
	$current_user_data = array(
375
		'isConnected' => Jetpack::is_user_connected( $current_user->ID ),
376
		'isMaster'    => $is_master_user,
377
		'username'    => $current_user->user_login,
378
		'id'          => $current_user->ID,
379
		'wpcomUser'   => $dotcom_data,
380
		'gravatar'    => get_avatar( $current_user->ID, 40, 'mm', '', array( 'force_display' => true ) ),
381
		'permissions' => array(
382
			'admin_page'         => current_user_can( 'jetpack_admin_page' ),
383
			'connect'            => current_user_can( 'jetpack_connect' ),
384
			'disconnect'         => current_user_can( 'jetpack_disconnect' ),
385
			'manage_modules'     => current_user_can( 'jetpack_manage_modules' ),
386
			'network_admin'      => current_user_can( 'jetpack_network_admin_page' ),
387
			'network_sites_page' => current_user_can( 'jetpack_network_sites_page' ),
388
			'edit_posts'         => current_user_can( 'edit_posts' ),
389
			'publish_posts'      => current_user_can( 'publish_posts' ),
390
			'manage_options'     => current_user_can( 'manage_options' ),
391
			'view_stats'		 => current_user_can( 'view_stats' ),
392
			'manage_plugins'	 => current_user_can( 'install_plugins' )
393
									&& current_user_can( 'activate_plugins' )
394
									&& current_user_can( 'update_plugins' )
395
									&& current_user_can( 'delete_plugins' ),
396
		),
397
	);
398
399
	return $current_user_data;
400
}
401