Completed
Push — try/search-config-via-wpadmin ( cb094f...014825 )
by
unknown
74:32 queued 64:33
created

Atomic_Admin_Menu   B

Complexity

Total Complexity 45

Size/Duplication

Total Lines 362
Duplicated Lines 9.12 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 33
loc 362
rs 8.8
c 0
b 0
f 0
wmc 45
lcom 1
cbo 4

22 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 19 2
A dequeue_scripts() 0 3 1
A is_rtl() 0 3 1
A reregister_menu_items() 18 18 3
A add_posts_menu() 0 3 1
A add_page_menu() 0 3 1
A add_plugins_menu() 0 4 1
A add_browse_sites_link() 0 10 3
A set_browse_sites_link_class() 12 12 3
A add_new_site_link() 0 9 3
A add_site_card_menu() 0 30 5
A set_site_card_menu_class() 0 20 5
A get_upsell_nudge() 0 18 2
A add_upgrades_menu() 3 25 3
A add_tools_menu() 0 4 1
A add_options_menu() 0 10 2
A add_appearance_menu() 0 6 1
A override_the_theme_installer() 0 8 3
A add_users_menu() 0 5 1
A add_gutenberg_menus() 0 5 1
A add_comments_menu() 0 3 1
A ajax_sidebar_state() 0 14 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 Atomic_Admin_Menu 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 Atomic_Admin_Menu, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Atomic Admin Menu file.
4
 *
5
 * @package automattic/jetpack
6
 */
7
8
namespace Automattic\Jetpack\Dashboard_Customizations;
9
10
use Automattic\Jetpack\Connection\Client;
11
use Jetpack_Plan;
12
13
require_once __DIR__ . '/class-admin-menu.php';
14
15
/**
16
 * Class Atomic_Admin_Menu.
17
 */
18
class Atomic_Admin_Menu extends Admin_Menu {
19
20
	/**
21
	 * Atomic_Admin_Menu constructor.
22
	 */
23
	protected function __construct() {
24
		parent::__construct();
25
26
		add_action( 'wp_enqueue_scripts', array( $this, 'dequeue_scripts' ), 20 );
27
		add_action( 'admin_enqueue_scripts', array( $this, 'dequeue_scripts' ), 20 );
28
		add_action( 'wp_ajax_sidebar_state', array( $this, 'ajax_sidebar_state' ) );
29
30
		if ( ! $this->is_api_request ) {
31
			add_filter( 'submenu_file', array( $this, 'override_the_theme_installer' ), 10, 2 );
32
		}
33
34
		add_action(
35
			'admin_menu',
36
			function () {
37
				remove_action( 'admin_menu', 'gutenberg_menu', 9 );
38
			},
39
			0
40
		);
41
	}
42
43
	/**
44
	 * Dequeues unnecessary scripts.
45
	 */
46
	public function dequeue_scripts() {
47
		wp_dequeue_script( 'a8c_wpcom_masterbar_overrides' ); // Initially loaded in modules/masterbar/masterbar/class-masterbar.php.
48
	}
49
50
	/**
51
	 * Determines whether the current locale is right-to-left (RTL).
52
	 *
53
	 * Performs the check against the current locale set on the WordPress.com's account settings.
54
	 * See `Masterbar::__construct` in `modules/masterbar/masterbar/class-masterbar.php`.
55
	 */
56
	public function is_rtl() {
57
		return get_user_option( 'jetpack_wpcom_is_rtl' );
58
	}
59
60
	/**
61
	 * Create the desired menu output.
62
	 */
63 View Code Duplication
	public function reregister_menu_items() {
64
		parent::reregister_menu_items();
65
66
		$this->add_my_home_menu();
67
68
		// Not needed outside of wp-admin.
69
		if ( ! $this->is_api_request ) {
70
			$this->add_browse_sites_link();
71
			$this->add_site_card_menu();
72
			$nudge = $this->get_upsell_nudge();
73
			if ( $nudge ) {
74
				parent::add_upsell_nudge( $nudge );
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (add_upsell_nudge() instead of reregister_menu_items()). Are you sure this is correct? If so, you might want to change this to $this->add_upsell_nudge().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
Documentation introduced by
$nudge is of type array<string,?,{"content...s_click_cta_name":"?"}>, but the function expects a object.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
75
			}
76
			$this->add_new_site_link();
77
		}
78
79
		ksort( $GLOBALS['menu'] );
80
	}
81
82
	/**
83
	 * Forces Posts menu to WPAdmin for Atomic sites only.
84
	 * Overloads `add_posts_menu` in parent class.
85
	 *
86
	 * @param bool $wp_admin Optional. Whether links should point to Calypso or wp-admin. Default false (Calypso).
87
	 */
88
	public function add_posts_menu( $wp_admin = false ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
89
		return false; // return explicit `false` to force WPAdmin links.
90
	}
91
92
	/**
93
	 * Forces Pages menu to WPAdmin for Atomic sites only.
94
	 * Overloads `add_page_menu` in parent class.
95
	 *
96
	 * @param bool $wp_admin Optional. Whether links should point to Calypso or wp-admin. Default false (Calypso).
97
	 */
98
	public function add_page_menu( $wp_admin = false ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
99
		return false; // return explicit `false` to force WPAdmin links.
100
	}
101
102
	/**
103
	 * Adds Plugins menu.
104
	 *
105
	 * @param bool $wp_admin Optional. Whether links should point to Calypso or wp-admin. Default false (Calypso).
106
	 */
107
	public function add_plugins_menu( $wp_admin = false ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
108
		// Plugins on Atomic sites are always managed on WP Admin.
109
		parent::add_plugins_menu( true );
110
	}
111
112
	/**
113
	 * Adds the site switcher link if user has more than one site.
114
	 */
115
	public function add_browse_sites_link() {
116
		$site_count = get_user_option( 'wpcom_site_count' );
117
		if ( ! $site_count || $site_count < 2 ) {
118
			return;
119
		}
120
121
		// Add the menu item.
122
		add_menu_page( __( 'site-switcher', 'jetpack' ), __( 'Browse sites', 'jetpack' ), 'read', 'https://wordpress.com/home', null, 'dashicons-arrow-left-alt2', 0 );
123
		add_filter( 'add_menu_classes', array( $this, 'set_browse_sites_link_class' ) );
124
	}
125
126
	/**
127
	 * Adds a custom element class for Site Switcher menu item.
128
	 *
129
	 * @param array $menu Associative array of administration menu items.
130
	 *
131
	 * @return array
132
	 */
133 View Code Duplication
	public function set_browse_sites_link_class( array $menu ) {
134
		foreach ( $menu as $key => $menu_item ) {
135
			if ( 'site-switcher' !== $menu_item[3] ) {
136
				continue;
137
			}
138
139
			$menu[ $key ][4] = add_cssclass( 'site-switcher', $menu_item[4] );
140
			break;
141
		}
142
143
		return $menu;
144
	}
145
146
	/**
147
	 * Adds a link to the menu to create a new site.
148
	 */
149
	public function add_new_site_link() {
150
		$site_count = get_user_option( 'wpcom_site_count' );
151
		if ( $site_count && $site_count > 1 ) {
152
			return;
153
		}
154
155
		$this->add_admin_menu_separator();
156
		add_menu_page( __( 'Add New Site', 'jetpack' ), __( 'Add New Site', 'jetpack' ), 'read', 'https://wordpress.com/start?ref=calypso-sidebar', null, 'dashicons-plus-alt' );
157
	}
158
159
	/**
160
	 * Adds site card component.
161
	 */
162
	public function add_site_card_menu() {
163
		$default   = 'data:image/svg+xml,' . rawurlencode( '<svg class="gridicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><title>Globe</title><rect fill-opacity="0" x="0" width="24" height="24"/><g><path fill="#fff" d="M12 2C6.477 2 2 6.477 2 12s4.477 10 10 10 10-4.477 10-10S17.523 2 12 2zm0 18l2-2 1-1v-2h-2v-1l-1-1H9v3l2 2v1.93c-3.94-.494-7-3.858-7-7.93l1 1h2v-2h2l3-3V6h-2L9 5v-.41C9.927 4.21 10.94 4 12 4s2.073.212 3 .59V6l-1 1v2l1 1 3.13-3.13c.752.897 1.304 1.964 1.606 3.13H18l-2 2v2l1 1h2l.286.286C18.03 18.06 15.24 20 12 20z"/></g></svg>' );
164
		$icon      = get_site_icon_url( 32, $default );
165
		$blog_name = get_option( 'blogname' ) !== '' ? get_option( 'blogname' ) : $this->domain;
166
167
		$badge = '';
168
		if ( function_exists( 'site_is_private' ) && site_is_private() ) {
169
			$badge .= sprintf(
170
				'<span class="site__badge site__badge-private">%s</span>',
171
				site_is_coming_soon() ? esc_html__( 'Coming Soon', 'jetpack' ) : esc_html__( 'Private', 'jetpack' )
172
			);
173
		}
174
175
		$site_card = '
176
<div class="site__info">
177
	<div class="site__title">%1$s</div>
178
	<div class="site__domain">%2$s</div>
179
	%3$s
180
</div>';
181
182
		$site_card = sprintf(
183
			$site_card,
184
			$blog_name,
185
			$this->domain,
186
			$badge
187
		);
188
189
		add_menu_page( 'site-card', $site_card, 'read', get_home_url(), null, $icon, 1 );
190
		add_filter( 'add_menu_classes', array( $this, 'set_site_card_menu_class' ) );
191
	}
192
193
	/**
194
	 * Adds a custom element class and id for Site Card's menu item.
195
	 *
196
	 * @param array $menu Associative array of administration menu items.
197
	 *
198
	 * @return array
199
	 */
200
	public function set_site_card_menu_class( array $menu ) {
201
		foreach ( $menu as $key => $menu_item ) {
202
			if ( 'site-card' !== $menu_item[3] ) {
203
				continue;
204
			}
205
206
			$classes = ' toplevel_page_site-card';
207
208
			// webclip.png is the default on WoA sites. Anything other than that means we have a custom site icon.
209
			if ( has_site_icon() && 'https://s0.wp.com/i/webclip.png' !== get_site_icon_url( 512 ) ) {
210
				$classes .= ' has-site-icon';
211
			}
212
213
			$menu[ $key ][4] = $menu_item[4] . $classes;
214
			$menu[ $key ][5] = 'toplevel_page_site_card';
215
			break;
216
		}
217
218
		return $menu;
219
	}
220
221
	/**
222
	 * Returns the first available upsell nudge.
223
	 *
224
	 * @return array
225
	 */
226
	public function get_upsell_nudge() {
227
		$jitm         = \Automattic\Jetpack\JITMS\JITM::get_instance();
228
		$message_path = 'calypso:sites:sidebar_notice';
229
		$message      = $jitm->get_messages( $message_path, wp_json_encode( array( 'message_path' => $message_path ) ), false );
0 ignored issues
show
Security Bug introduced by
It seems like wp_json_encode(array('me...ath' => $message_path)) targeting wp_json_encode() can also be of type false; however, Automattic\Jetpack\JITMS...on_JITM::get_messages() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
Security Bug introduced by
It seems like wp_json_encode(array('me...ath' => $message_path)) targeting wp_json_encode() can also be of type false; however, Automattic\Jetpack\JITMS...on_JITM::get_messages() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
230
231
		if ( isset( $message[0] ) ) {
232
			$message = $message[0];
233
			return array(
234
				'content'                      => $message->content->message,
235
				'cta'                          => $message->CTA->message, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
236
				'link'                         => $message->CTA->link, // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
237
				'tracks_impression_event_name' => $message->tracks->display->name,
238
				'tracks_impression_cta_name'   => $message->tracks->display->props->cta_name,
239
				'tracks_click_event_name'      => $message->tracks->click->name,
240
				'tracks_click_cta_name'        => $message->tracks->click->props->cta_name,
241
			);
242
		}
243
	}
244
245
	/**
246
	 * Adds Upgrades menu.
247
	 *
248
	 * @param string $plan The current WPCOM plan of the blog.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $plan not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
249
	 */
250
	public function add_upgrades_menu( $plan = null ) {
251
		$products = Jetpack_Plan::get();
252
		if ( array_key_exists( 'product_name_short', $products ) ) {
253
			$plan = $products['product_name_short'];
254
		}
255
		parent::add_upgrades_menu( $plan );
256
257
		$last_upgrade_submenu_position = $this->get_submenu_item_count( 'paid-upgrades.php' );
258
259
		add_submenu_page( 'paid-upgrades.php', __( 'Domains', 'jetpack' ), __( 'Domains', 'jetpack' ), 'manage_options', 'https://wordpress.com/domains/manage/' . $this->domain, null, $last_upgrade_submenu_position - 1 );
260
261
		/**
262
		 * Whether to show the WordPress.com Emails submenu under the main Upgrades menu.
263
		 *
264
		 * @use add_filter( 'jetpack_show_wpcom_upgrades_email_menu', '__return_true' );
265
		 * @module masterbar
266
		 *
267
		 * @since 9.7.0
268
		 *
269
		 * @param bool $show_wpcom_upgrades_email_menu Load the WordPress.com Emails submenu item. Default to false.
270
		 */
271 View Code Duplication
		if ( apply_filters( 'jetpack_show_wpcom_upgrades_email_menu', false ) ) {
272
			add_submenu_page( 'paid-upgrades.php', __( 'Emails', 'jetpack' ), __( 'Emails', 'jetpack' ), 'manage_options', 'https://wordpress.com/email/' . $this->domain, null, $last_upgrade_submenu_position );
273
		}
274
	}
275
276
	/**
277
	 * Adds Tools menu.
278
	 *
279
	 * @param bool $wp_admin_import Optional. Whether Import link should point to Calypso or wp-admin. Default false (Calypso).
280
	 * @param bool $wp_admin_export Optional. Whether Export link should point to Calypso or wp-admin. Default false (Calypso).
281
	 */
282
	public function add_tools_menu( $wp_admin_import = false, $wp_admin_export = false ) {  // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
283
		// Export on Atomic sites is always handled on WP Admin.
284
		parent::add_tools_menu( $wp_admin_import, true );
285
	}
286
287
	/**
288
	 * Adds Settings menu.
289
	 *
290
	 * @param bool $wp_admin Optional. Whether links should point to Calypso or wp-admin. Default false (Calypso).
291
	 */
292
	public function add_options_menu( $wp_admin = false ) {
293
		parent::add_options_menu( $wp_admin );
294
295
		add_submenu_page( 'options-general.php', esc_attr__( 'Hosting Configuration', 'jetpack' ), __( 'Hosting Configuration', 'jetpack' ), 'manage_options', 'https://wordpress.com/hosting-config/' . $this->domain, null, 6 );
296
297
		// No need to add a menu linking to WP Admin if there is already one.
298
		if ( ! $wp_admin ) {
299
			add_submenu_page( 'options-general.php', esc_attr__( 'Advanced Writing', 'jetpack' ), __( 'Advanced Writing', 'jetpack' ), 'manage_options', 'options-writing.php' );
300
		}
301
	}
302
303
	/**
304
	 * Adds Appearance menu.
305
	 *
306
	 * @param bool $wp_admin_themes Optional. Whether Themes link should point to Calypso or wp-admin. Default false (Calypso).
307
	 * @param bool $wp_admin_customize Optional. Whether Customize link should point to Calypso or wp-admin. Default false (Calypso).
308
	 */
309
	public function add_appearance_menu( $wp_admin_themes = false, $wp_admin_customize = false ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
310
		// Customize on Atomic sites is always done on WP Admin.
311
		parent::add_appearance_menu( $wp_admin_themes, true );
312
313
		add_submenu_page( 'themes.php', esc_attr__( 'Add New Theme', 'jetpack' ), __( 'Add New Theme', 'jetpack' ), 'install_themes', 'theme-install.php', null, 1 );
314
	}
315
316
	/**
317
	 * Override the global submenu_file for theme-install.php page so the WP Admin menu item gets highlighted correctly.
318
	 *
319
	 * @param string $submenu_file The current pages $submenu_file global variable value.
320
	 * @return string | null
321
	 */
322
	public function override_the_theme_installer( $submenu_file ) {
323
		global $pagenow;
324
325
		if ( 'themes.php' === $submenu_file && 'theme-install.php' === $pagenow ) {
326
			return null;
327
		}
328
		return $submenu_file;
329
	}
330
331
	/**
332
	 * Adds Users menu.
333
	 *
334
	 * @param bool $wp_admin Optional. Whether links should point to Calypso or wp-admin. Default false (Calypso).
335
	 */
336
	public function add_users_menu( $wp_admin = false ) {
337
		parent::add_users_menu( $wp_admin );
338
339
		add_submenu_page( 'users.php', esc_attr__( 'Advanced Users Management', 'jetpack' ), __( 'Advanced Users Management', 'jetpack' ), 'list_users', 'users.php', null, 2 );
340
	}
341
342
	/**
343
	 * Also remove the Gutenberg plugin menu.
344
	 *
345
	 * @param bool $wp_admin Optional. Whether links should point to Calypso or wp-admin. Default false (Calypso).
346
	 */
347
	public function add_gutenberg_menus( $wp_admin = false ) {
348
		// Always remove the Gutenberg menu.
349
		remove_menu_page( 'gutenberg' );
350
		parent::add_gutenberg_menus( $wp_admin );
351
	}
352
353
	/**
354
	 * Always use WP Admin for comments.
355
	 *
356
	 * @param bool $wp_admin Optional. Whether links should point to Calypso or wp-admin. Default false (Calypso).
357
	 */
358
	public function add_comments_menu( $wp_admin = false ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
359
		parent::add_comments_menu( true );
360
	}
361
362
	/**
363
	 * Saves the sidebar state ( expanded / collapsed ) via an ajax request.
364
	 */
365
	public function ajax_sidebar_state() {
366
		$expanded = filter_var( $_REQUEST['expanded'], FILTER_VALIDATE_BOOLEAN ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
367
		Client::wpcom_json_api_request_as_user(
368
			'/me/preferences',
369
			'2',
370
			array(
371
				'method' => 'POST',
372
			),
373
			(object) array( 'calypso_preferences' => (object) array( 'sidebarCollapsed' => ! $expanded ) ),
374
			'wpcom'
375
		);
376
377
		wp_die();
378
	}
379
}
380
381