enqueue_script_specific_css()   B
last analyzed

Complexity

Conditions 11
Paths 23

Size

Total Lines 47
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 25
c 1
b 0
f 0
nc 23
nop 1
dl 0
loc 47
rs 7.3166

How to fix   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
 * WP ADMIN assets will be enqueued here.
4
 *
5
 * @package monsterinsights
6
 */
7
8
/**
9
 * Class MonsterInsights_Admin_Assets
10
 * This class is responsible for load CSS and JS in admin panel.
11
 */
12
class MonsterInsights_Admin_Assets {
13
	/**
14
	 * MonsterInsights handles.
15
	 */
16
	private $own_handles = array(
17
		'monsterinsights-vue-script',
18
		'monsterinsights-vue-frontend',
19
		'monsterinsights-vue-reports',
20
		'monsterinsights-vue-widget',
21
	);
22
23
	/**
24
	 * Store manifest.json file content.
25
	 *
26
	 * @var array
27
	 */
28
	private static $manifest_data;
29
30
	/**
31
	 * Class constructor.
32
	 */
33
	public function __construct() {
34
		add_filter( 'script_loader_tag', array( $this, 'script_loader_tag' ), 99999, 3 );
35
36
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_styles' ) );
37
38
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_scripts' ) );
39
40
		$this->get_manifest_data();
41
	}
42
43
	/**
44
	 * Update script tag.
45
	 * The vue code needs type=module.
46
	 */
47
	public function script_loader_tag( $tag, $handle, $src ) {
48
49
		if ( ! in_array( $handle, $this->own_handles ) ) {
50
			return $tag;
51
		}
52
53
		// Change the script tag by adding type="module" and return it.
54
		$html = str_replace( '></script>', ' type="module"></script>', $tag );
55
56
		$domain = monsterinsights_is_pro_version() ? 'ga-premium' : 'google-analytics-for-wordpress';
57
		$html   = monsterinsights_get_printable_translations( $domain ) . $html;
58
59
		return $html;
60
	}
61
62
	/**
63
	 * Loads styles for all MonsterInsights-based Administration Screens.
64
	 *
65
	 * @return null Return early if not on the proper screen.
66
	 */
67
	public function admin_styles() {
68
69
		$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
70
71
		// Load Common admin styles.
72
		wp_register_style( 'monsterinsights-admin-common-style', plugins_url( 'assets/css/admin-common' . $suffix . '.css', MONSTERINSIGHTS_PLUGIN_FILE ), array(), monsterinsights_get_asset_version() );
73
		wp_enqueue_style( 'monsterinsights-admin-common-style' );
74
75
		// Get current screen.
76
		$screen = get_current_screen();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $screen is correct as get_current_screen() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
77
78
		// Bail if we're not on a MonsterInsights screen.
79
		if ( empty( $screen->id ) || strpos( $screen->id, 'monsterinsights' ) === false ) {
80
			return;
81
		}
82
83
		// For the settings pages, load the Vue app scripts.
84
		if ( monsterinsights_is_settings_page() ) {
85
			if ( ! defined( 'MONSTERINSIGHTS_LOCAL_JS_URL' ) ) {
86
				+$this->enqueue_script_specific_css( 'src/modules/settings/settings.js' );
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->enqueue_script_sp.../settings/settings.js') targeting MonsterInsights_Admin_As...e_script_specific_css() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
87
			}
88
89
			// Don't load other scripts on the settings page.
90
			return;
91
		}
92
93
		// For the report pages, load the Vue app scripts.
94
		if ( monsterinsights_is_reports_page() ) {
95
			if ( ! defined( 'MONSTERINSIGHTS_LOCAL_JS_URL' ) ) {
96
				$this->enqueue_script_specific_css( 'src/modules/reports/reports.js' );
97
			}
98
99
			return;
100
		}
101
102
		// Tooltips
103
		wp_enqueue_script( 'jquery-ui-tooltip' );
104
	}
105
106
	/**
107
	 * Loads scripts for all MonsterInsights-based Administration Screens.
108
	 *
109
	 * @return null Return early if not on the proper screen.
110
	 */
111
	public function admin_scripts() {
112
113
		// Our Common Admin JS.
114
		$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
115
116
		wp_enqueue_script( 'monsterinsights-admin-common-script', plugins_url( 'assets/js/admin-common' . $suffix . '.js', MONSTERINSIGHTS_PLUGIN_FILE ), array( 'jquery' ), monsterinsights_get_asset_version(), true );
117
118
		wp_localize_script(
119
			'monsterinsights-admin-common-script',
120
			'monsterinsights_admin_common',
121
			array(
122
				'ajax'                 => admin_url( 'admin-ajax.php' ),
123
				'dismiss_notice_nonce' => wp_create_nonce( 'monsterinsights-dismiss-notice' ),
124
			)
125
		);
126
127
		// Get current screen.
128
		$screen = get_current_screen();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $screen is correct as get_current_screen() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
129
130
		// Bail if we're not on a MonsterInsights screen.
131
		if ( empty( $screen->id ) || strpos( $screen->id, 'monsterinsights' ) === false ) {
132
			return;
133
		}
134
135
		$version_path = monsterinsights_is_pro_version() ? 'pro' : 'lite';
136
137
		// For the settings page, load the Vue app.
138
		if ( monsterinsights_is_settings_page() ) {
139
			$app_js_url = self::get_js_url( 'src/modules/settings/settings.js' );
140
			wp_register_script( 'monsterinsights-vue-script', $app_js_url, array( 'wp-i18n' ), monsterinsights_get_asset_version(), true );
141
			wp_enqueue_script( 'monsterinsights-vue-script' );
142
143
			$plugins         = get_plugins();
144
			$install_amp_url = false;
145
			if ( monsterinsights_can_install_plugins() ) {
146
				$amp_key = 'amp/amp.php';
147
				if ( array_key_exists( $amp_key, $plugins ) ) {
148
					$install_amp_url = wp_nonce_url( self_admin_url( 'plugins.php?action=activate&plugin=' . $amp_key ), 'activate-plugin_' . $amp_key );
149
				} else {
150
					$install_amp_url = wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=amp' ), 'install-plugin_amp' );
151
				}
152
			}
153
154
			$install_woocommerce_url = false;
155
			if ( monsterinsights_can_install_plugins() ) {
156
				$woo_key = 'woocommerce/woocommerce.php';
157
				if ( array_key_exists( $woo_key, $plugins ) ) {
158
					$install_woocommerce_url = wp_nonce_url( self_admin_url( 'plugins.php?action=activate&plugin=' . $woo_key ), 'activate-plugin_' . $woo_key );
159
				} else {
160
					$install_woocommerce_url = wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=woocommerce' ), 'install-plugin_woocommerce' );
161
				}
162
			}
163
164
			$prepared_dimensions = array();
165
			if ( class_exists( 'MonsterInsights_Admin_Custom_Dimensions' ) ) {
166
				$dimensions          = new MonsterInsights_Admin_Custom_Dimensions();
0 ignored issues
show
Bug introduced by
The type MonsterInsights_Admin_Custom_Dimensions was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
167
				$dimensions          = $dimensions->custom_dimensions();
168
				$prepared_dimensions = array();
169
				foreach ( $dimensions as $dimension_type => $dimension ) {
170
					$dimension['type']     = $dimension_type;
171
					$prepared_dimensions[] = $dimension;
172
				}
173
			}
174
175
			$is_authed = ( MonsterInsights()->auth->is_authed() || MonsterInsights()->auth->is_network_authed() );
0 ignored issues
show
Bug Best Practice introduced by
The property $auth is declared protected in MonsterInsights_Lite. Since you implement __get, consider adding a @property or @property-read.
Loading history...
176
177
			wp_localize_script(
178
				'monsterinsights-vue-script',
179
				'monsterinsights',
180
				array(
181
					'ajax'                            => admin_url( 'admin-ajax.php' ),
182
					'nonce'                           => wp_create_nonce( 'mi-admin-nonce' ),
183
					'network'                         => is_network_admin(),
184
					'assets'                          => plugins_url( $version_path . '/assets/vue', MONSTERINSIGHTS_PLUGIN_FILE ),
185
					'roles'                           => monsterinsights_get_roles(),
186
					'roles_manage_options'            => monsterinsights_get_manage_options_roles(),
187
					'shareasale_id'                   => monsterinsights_get_shareasale_id(),
188
					'shareasale_url'                  => monsterinsights_get_shareasale_url( monsterinsights_get_shareasale_id(), '' ),
189
					'addons_url'                      => is_multisite() ? network_admin_url( 'admin.php?page=monsterinsights_network#/addons' ) : admin_url( 'admin.php?page=monsterinsights_settings#/addons' ),
190
					'seo_settings_page_url'           => is_multisite() ? network_admin_url( 'admin.php?page=monsterinsights_network#/seo' ) : admin_url( 'admin.php?page=monsterinsights_settings#/seo' ),
191
					'aioseo_dashboard_url'            => is_multisite() ? network_admin_url( 'admin.php?page=aioseo' ) : admin_url( 'admin.php?page=aioseo' ),
192
					'wp_plugins_page_url'             => is_multisite() ? network_admin_url( 'plugins.php' ) : admin_url( 'plugins.php' ),
193
					'email_summary_url'               => admin_url( 'admin.php?monsterinsights_email_preview&monsterinsights_email_template=summary' ),
194
					'install_amp_url'                 => $install_amp_url,
195
					'install_woo_url'                 => $install_woocommerce_url,
196
					'dimensions'                      => $prepared_dimensions,
197
					'wizard_url'                      => is_network_admin() ? network_admin_url( 'index.php?page=monsterinsights-onboarding' ) : admin_url( 'index.php?page=monsterinsights-onboarding' ),
198
					'install_plugins'                 => monsterinsights_can_install_plugins(),
199
					'unfiltered_html'                 => current_user_can( 'unfiltered_html' ),
200
					'activate_nonce'                  => wp_create_nonce( 'monsterinsights-activate' ),
201
					'deactivate_nonce'                => wp_create_nonce( 'monsterinsights-deactivate' ),
202
					'install_nonce'                   => wp_create_nonce( 'monsterinsights-install' ),
203
					// Used to add notices for future deprecations.
204
					'versions'                        => monsterinsights_get_php_wp_version_warning_data(),
205
					'plugin_version'                  => MONSTERINSIGHTS_VERSION,
206
					'is_admin'                        => true,
207
					'admin_email'                     => get_option( 'admin_email' ),
208
					'site_url'                        => get_site_url(),
209
					'reports_url'                     => add_query_arg( 'page', 'monsterinsights_reports', admin_url( 'admin.php' ) ),
210
					'ecommerce_report_url'            => add_query_arg( 'page', 'monsterinsights_reports#/ecommerce', admin_url( 'admin.php' ) ),
211
					'ecommerce_settings_tab_url'      => add_query_arg( 'page', 'monsterinsights_settings#/ecommerce', admin_url( 'admin.php' ) ),
212
					'first_run_notice'                => apply_filters( 'monsterinsights_settings_first_time_notice_hide', monsterinsights_get_option( 'monsterinsights_first_run_notice' ) ),
213
					'getting_started_url'             => is_network_admin() ? network_admin_url( 'admin.php?page=monsterinsights_network#/about' ) : admin_url( 'admin.php?page=monsterinsights_settings#/about/getting-started' ),
214
					'authed'                          => $is_authed,
215
					'new_pretty_link_url'             => admin_url( 'post-new.php?post_type=pretty-link' ),
216
					'wpmailsmtp_admin_url'            => admin_url( 'admin.php?page=wp-mail-smtp' ),
217
					'load_headline_analyzer_settings' => monsterinsights_load_gutenberg_app() ? 'true' : 'false',
218
					'exit_url'                        => add_query_arg( 'page', 'monsterinsights_settings', admin_url( 'admin.php' ) ),
219
					'timezone'                        => date( 'e' ),
220
					'funnelkit_stripe_woo_page_url'   => admin_url( 'admin.php?page=wc-settings&tab=fkwcs_api_settings' ),
221
					'funnelkit_stripe_woo_nonce'      => wp_create_nonce( 'monsterinsights-funnelkit-stripe-woo-nonce' ),
222
				)
223
			);
224
225
			// Don't load other scripts on the settings page.
226
			return;
227
		}
228
229
		// For the report pages, load the Vue app.
230
		if ( monsterinsights_is_reports_page() ) {
231
232
			$app_js_url = self::get_js_url( 'src/modules/reports/reports.js' );
233
			wp_register_script( 'monsterinsights-vue-reports', $app_js_url, array( 'wp-i18n' ), monsterinsights_get_asset_version(), true );
234
			wp_enqueue_script( 'monsterinsights-vue-reports' );
235
236
			// We do not have a current auth.
237
			$auth      = MonsterInsights()->auth;
238
			$site_auth = $auth->get_viewname();
239
			$ms_auth   = is_multisite() && $auth->get_network_viewname();
240
241
			// Localize the script with the necessary data.
242
			wp_localize_script(
243
				'monsterinsights-vue-reports',
244
				'monsterinsights',
245
				array(
246
					'ajax'                => admin_url( 'admin-ajax.php' ),
247
					'nonce'               => wp_create_nonce( 'mi-admin-nonce' ),
248
					'rest_nonce'          => wp_create_nonce( 'wp_rest' ),
249
					'rest_url'            => get_rest_url(),
250
					'network'             => is_network_admin(),
251
					'translations'        => wp_get_jed_locale_data( monsterinsights_is_pro_version() ? 'ga-premium' : 'google-analytics-for-wordpress' ),
252
					'assets'              => plugins_url( $version_path . '/assets/vue', MONSTERINSIGHTS_PLUGIN_FILE ),
253
					'pro_assets'          => plugins_url( $version_path . '/assets', MONSTERINSIGHTS_PLUGIN_FILE ),
254
					'shareasale_id'       => monsterinsights_get_shareasale_id(),
255
					'shareasale_url'      => monsterinsights_get_shareasale_url( monsterinsights_get_shareasale_id(), '' ),
256
					'addons_url'          => is_multisite() ? network_admin_url( 'admin.php?page=monsterinsights_network#/addons' ) : admin_url( 'admin.php?page=monsterinsights_settings#/addons' ),
257
					'timezone'            => date('e'), // phpcs:ignore
258
					'authed'              => $site_auth || $ms_auth,
259
					'settings_url'        => add_query_arg( 'page', 'monsterinsights_settings', admin_url( 'admin.php' ) ),
260
					// Used to add notices for future deprecations.
261
					'versions'            => monsterinsights_get_php_wp_version_warning_data(),
262
					'plugin_version'      => MONSTERINSIGHTS_VERSION,
263
					'is_admin'            => true,
264
					'admin_email'         => get_option( 'admin_email' ),
265
					'site_url'            => get_site_url(),
266
					'wizard_url'          => is_network_admin() ? network_admin_url( 'index.php?page=monsterinsights-onboarding' ) : admin_url( 'index.php?page=monsterinsights-onboarding' ),
267
					'install_nonce'       => wp_create_nonce( 'monsterinsights-install' ),
268
					'activate_nonce'      => wp_create_nonce( 'monsterinsights-activate' ),
269
					'deactivate_nonce'    => wp_create_nonce( 'monsterinsights-deactivate' ),
270
					'update_settings'     => current_user_can( 'monsterinsights_save_settings' ),
271
					'migrated'            => monsterinsights_get_option( 'gadwp_migrated', 0 ),
272
					'yearinreview'        => monsterinsights_yearinreview_dates(),
273
					'reports_url'         => add_query_arg( 'page', 'monsterinsights_reports', admin_url( 'admin.php' ) ),
274
					'feedback'            => MonsterInsights_Feature_Feedback::get_settings(),
275
					'addons_pre_check'    => array(
276
						'ai_insights' => is_plugin_active( 'monsterinsights-ai-insights/monsterinsights-ai-insights.php' ),
277
					),
278
				)
279
			);
280
281
			// Load the script with specific translations.
282
			wp_set_script_translations(
283
				'monsterinsights-vue-reports',
284
				monsterinsights_is_pro_version() ? 'ga-premium' : 'google-analytics-for-wordpress',
285
				MONSTERINSIGHTS_PLUGIN_DIR . 'languages'
286
			);
287
288
			return;
289
		}
290
291
		// ublock notice
292
		add_action( 'admin_print_footer_scripts', array( $this, 'monsterinsights_settings_ublock_error_js' ), 9999999 );
293
	}
294
295
	/**
296
	 * Need to identify why this function is using.
297
	 */
298
	public function monsterinsights_settings_ublock_error_js() {
299
		echo "<script type='text/javascript'>\n";
300
		echo "jQuery( document ).ready( function( $ ) {
301
				if ( window.uorigindetected == null){
302
				   $('#monsterinsights-ublock-origin-error').show();
303
				   $('.monsterinsights-nav-tabs').hide();
304
				   $('.monsterinsights-nav-container').hide();
305
				   $('#monsterinsights-addon-heading').hide();
306
				   $('#monsterinsights-addons').hide();
307
				   $('#monsterinsights-reports').hide();
308
				}
309
			});";
310
		echo "\n</script>";
311
	}
312
313
	/**
314
	 * Load CSS from manifest.json
315
	 */
316
	public static function enqueue_script_specific_css( $js_file_path ) {
317
		if ( defined( 'MONSTERINSIGHTS_LOCAL_JS_URL' ) ) {
318
			return;
319
		}
320
321
		$version_path = monsterinsights_is_pro_version() ? 'pro' : 'lite';
322
		$plugin_path  = plugin_dir_path( MONSTERINSIGHTS_PLUGIN_FILE );
323
324
		if ( ! isset( self::$manifest_data[ $js_file_path ] ) ) {
325
			return;
326
		}
327
328
		$js_imports    = self::$manifest_data[ $js_file_path ]['imports'];
329
		$css_file_path = $plugin_path . $version_path . '/assets/vue/';
330
331
		// Add JS own CSS file.
332
		if ( isset( self::$manifest_data[ $js_file_path ]['css'] ) ) {
333
			self::add_js_own_css_files( self::$manifest_data[ $js_file_path ]['css'], $version_path );
334
		}
335
336
		// Loop through all imported js file of entry file.
337
		foreach ( $js_imports as $js_filename ) {
338
			// Check imported file available in manifest.json
339
			if ( ! isset( self::$manifest_data[ $js_filename ] ) ) {
340
				continue;
341
			}
342
343
			// Check imported js file has it's own css.
344
			if ( ! isset( self::$manifest_data[ $js_filename ]['css'] ) ) {
345
				continue;
346
			}
347
348
			$js_file_css = self::$manifest_data[ $js_filename ]['css'];
349
350
			// css must be array.
351
			if ( ! is_array( $js_file_css ) ) {
352
				continue;
353
			}
354
355
			// Loop to css files of a imported js file.
356
			foreach ( $js_file_css as $css_hash_name ) {
357
				if ( file_exists( $css_file_path . $css_hash_name ) ) {
358
					wp_enqueue_style(
359
						'monsterinsights-style-' . basename( $css_hash_name ),
360
						plugins_url( $version_path . '/assets/vue/' . $css_hash_name, MONSTERINSIGHTS_PLUGIN_FILE ),
361
						array(),
362
						monsterinsights_get_asset_version()
363
					);
364
				}
365
			}
366
		}
367
	}
368
369
	/**
370
	 * Add JS it's own CSS build file.
371
	 */
372
	private static function add_js_own_css_files( $css_files, $version_path ) {
373
		foreach ( $css_files as $css_filename ) {
374
			wp_enqueue_style(
375
				'monsterinsights-style-' . basename( $css_filename ),
376
				plugins_url( $version_path . '/assets/vue/' . $css_filename, MONSTERINSIGHTS_PLUGIN_FILE ),
377
				array(),
378
				monsterinsights_get_asset_version()
379
			);
380
		}
381
	}
382
383
	/**
384
	 * Get JS build file URL of a entry file.
385
	 *
386
	 * @return string
387
	 */
388
	public static function get_js_url( $path ) {
389
		if ( ! $path ) {
390
			return;
391
		}
392
393
		if ( defined( 'MONSTERINSIGHTS_LOCAL_JS_URL' ) && MONSTERINSIGHTS_LOCAL_JS_URL ) {
0 ignored issues
show
Bug introduced by
The constant MONSTERINSIGHTS_LOCAL_JS_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
394
			return MONSTERINSIGHTS_LOCAL_JS_URL . $path;
395
		}
396
397
		// If the file is not available on manifest.
398
		if ( ! isset( self::$manifest_data[ $path ] ) ) {
399
			return;
400
		}
401
402
		$js_file      = self::$manifest_data[ $path ]['file'];
403
		$version_path = monsterinsights_is_pro_version() ? 'pro' : 'lite';
404
405
		return plugins_url( $version_path . '/assets/vue/' . $js_file, MONSTERINSIGHTS_PLUGIN_FILE );
406
	}
407
408
	/**
409
	 * Fetch manifest.json data and store it to array for future use.
410
	 *
411
	 * @return void
412
	 */
413
	private function get_manifest_data() {
414
		$version_path  = monsterinsights_is_pro_version() ? 'pro' : 'lite';
415
		$plugin_path   = plugin_dir_path( MONSTERINSIGHTS_PLUGIN_FILE );
416
		$manifest_path = $plugin_path . $version_path . '/assets/vue/manifest.json';
417
418
		// Return if manifest.json not exists.
419
		if ( ! file_exists( $manifest_path ) ) {
420
			return;
421
		}
422
423
		self::$manifest_data = json_decode( file_get_contents( $manifest_path ), true );
424
	}
425
}
426
427
new MonsterInsights_Admin_Assets();
428