Completed
Push — iterate/calypsoify ( 2ba5fb...4d78ff )
by George
146:23 queued 138:29
created

cdnize_plugin_assets()   C

Complexity

Conditions 11
Paths 26

Size

Total Lines 52

Duplication

Lines 24
Ratio 46.15 %

Importance

Changes 0
Metric Value
cc 11
nc 26
nop 2
dl 24
loc 52
rs 6.9006
c 0
b 0
f 0

How to fix   Long Method    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
 * Module Name: Asset CDN
4
 * Module Description: Serve static assets from our servers
5
 * Sort Order: 26
6
 * Recommendation Order: 1
7
 * First Introduced: 6.6
8
 * Requires Connection: No
9
 * Auto Activate: No
10
 * Module Tags: Photos and Videos, Appearance, Recommended
11
 * Feature: Recommended, Appearance
12
 * Additional Search Queries: photon, image, cdn, performance, speed, assets
13
 */
14
15
$GLOBALS['concatenate_scripts'] = false;
16
17
Jetpack::dns_prefetch( array(
18
	'//c0.wp.com',
19
) );
20
21
class Jetpack_Photon_Static_Assets_CDN {
22
	const CDN = 'https://c0.wp.com/';
23
24
	/**
25
	 * Sets up action handlers needed for Jetpack CDN.
26
	 */
27
	public static function go() {
28
		add_action( 'wp_print_scripts', array( __CLASS__, 'cdnize_assets' ) );
29
		add_action( 'wp_print_styles', array( __CLASS__, 'cdnize_assets' ) );
30
		add_action( 'admin_print_scripts', array( __CLASS__, 'cdnize_assets' ) );
31
		add_action( 'admin_print_styles', array( __CLASS__, 'cdnize_assets' ) );
32
		add_action( 'wp_footer', array( __CLASS__, 'cdnize_assets' ) );
33
	}
34
35
	/**
36
	 * Sets up CDN URLs for assets that are enqueued by the WordPress Core.
37
	 */
38
	public static function cdnize_assets() {
39
		global $wp_scripts, $wp_styles, $wp_version;
40
41
		/**
42
		 * Filters Jetpack CDN's Core version number and locale. Can be used to override the values
43
		 * that Jetpack uses to retrieve assets. Expects the values to be returned in an array.
44
		 *
45
		 * @module photon-cdn
46
		 *
47
		 * @since 6.6.0
48
		 *
49
		 * @param array $values array( $version  = core assets version, i.e. 4.9.8, $locale = desired locale )
50
		 */
51
		list( $version, $locale ) = apply_filters(
0 ignored issues
show
Unused Code introduced by
The assignment to $locale is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
52
			'jetpack_cdn_core_version_and_locale',
53
			array( $wp_version, get_locale() )
54
		);
55
56
		if ( self::is_public_version( $version ) ) {
57
			$site_url = trailingslashit( site_url() );
58 View Code Duplication
			foreach ( $wp_scripts->registered as $handle => $thing ) {
59
				if ( wp_startswith( $thing->src, self::CDN ) ) {
60
					continue;
61
				}
62
				$src = ltrim( str_replace( $site_url, '', $thing->src ), '/' );
63
				if ( self::is_js_or_css_file( $src ) && in_array( substr( $src, 0, 9 ), array( 'wp-admin/', 'wp-includ' ) ) ) {
64
					$wp_scripts->registered[ $handle ]->src = sprintf( self::CDN . 'c/%1$s/%2$s', $version, $src );
65
					$wp_scripts->registered[ $handle ]->ver = null;
66
				}
67
			}
68 View Code Duplication
			foreach ( $wp_styles->registered as $handle => $thing ) {
69
				if ( wp_startswith( $thing->src, self::CDN ) ) {
70
					continue;
71
				}
72
				$src = ltrim( str_replace( $site_url, '', $thing->src ), '/' );
73
				if ( self::is_js_or_css_file( $src ) && in_array( substr( $src, 0, 9 ), array( 'wp-admin/', 'wp-includ' ) ) ) {
74
					$wp_styles->registered[ $handle ]->src = sprintf( self::CDN . 'c/%1$s/%2$s', $version, $src );
75
					$wp_styles->registered[ $handle ]->ver = null;
76
				}
77
			}
78
		}
79
80
		self::cdnize_plugin_assets( 'jetpack', JETPACK__VERSION );
81
		if ( class_exists( 'WooCommerce' ) ) {
82
			self::cdnize_plugin_assets( 'woocommerce', WC_VERSION );
83
		}
84
	}
85
86
	/**
87
	 * Sets up CDN URLs for supported plugin assets.
88
	 *
89
	 * @param String $plugin_slug plugin slug string.
90
	 * @param String $current_version plugin version string.
91
	 * @return null|bool
92
	 */
93
	public static function cdnize_plugin_assets( $plugin_slug, $current_version ) {
94
		global $wp_scripts, $wp_styles;
95
96
		/**
97
		 * Filters Jetpack CDN's plugin slug and version number. Can be used to override the values
98
		 * that Jetpack uses to retrieve assets. For example, when testing a development version of Jetpack
99
		 * the assets are not yet published, so you may need to override the version value to either
100
		 * trunk, or the latest available version. Expects the values to be returned in an array.
101
		 *
102
		 * @module photon-cdn
103
		 *
104
		 * @since 6.6.0
105
		 *
106
		 * @param array $values array( $slug = the plugin repository slug, i.e. jetpack, $version = the plugin version, i.e. 6.6 )
107
		 */
108
		list( $plugin_slug, $current_version ) = apply_filters(
109
			'jetpack_cdn_plugin_slug_and_version',
110
			array( $plugin_slug, $current_version )
111
		);
112
113
		$assets               = self::get_plugin_assets( $plugin_slug, $current_version );
114
		$plugin_directory_url = plugins_url() . '/' . $plugin_slug . '/';
115
116
		if ( is_wp_error( $assets ) || ! is_array( $assets ) ) {
117
			return false;
118
		}
119
120 View Code Duplication
		foreach ( $wp_scripts->registered as $handle => $thing ) {
121
			if ( wp_startswith( $thing->src, self::CDN ) ) {
122
				continue;
123
			}
124
			if ( wp_startswith( $thing->src, $plugin_directory_url ) ) {
125
				$local_path = substr( $thing->src, strlen( $plugin_directory_url ) );
126
				if ( in_array( $local_path, $assets, true ) ) {
127
					$wp_scripts->registered[ $handle ]->src = sprintf( self::CDN . 'p/%1$s/%2$s/%3$s', $plugin_slug, $current_version, $local_path );
128
					$wp_scripts->registered[ $handle ]->ver = null;
129
				}
130
			}
131
		}
132 View Code Duplication
		foreach ( $wp_styles->registered as $handle => $thing ) {
133
			if ( wp_startswith( $thing->src, self::CDN ) ) {
134
				continue;
135
			}
136
			if ( wp_startswith( $thing->src, $plugin_directory_url ) ) {
137
				$local_path = substr( $thing->src, strlen( $plugin_directory_url ) );
138
				if ( in_array( $local_path, $assets, true ) ) {
139
					$wp_styles->registered[ $handle ]->src = sprintf( self::CDN . 'p/%1$s/%2$s/%3$s', $plugin_slug, $current_version, $local_path );
140
					$wp_styles->registered[ $handle ]->ver = null;
141
				}
142
			}
143
		}
144
	}
145
146
	/**
147
	 * Returns cdn-able assets for a given plugin.
148
	 *
149
	 * @param string $plugin plugin slug string.
150
	 * @param string $version plugin version number string.
151
	 * @return array
152
	 */
153
	public static function get_plugin_assets( $plugin, $version ) {
154
		if ( 'jetpack' === $plugin && JETPACK__VERSION === $version ) {
155
			$assets = array(); // The variable will be redefined in the included file.
156
157
			include JETPACK__PLUGIN_DIR . 'modules/photon-cdn/jetpack-manifest.php';
158
			return $assets;
159
		}
160
161
		/**
162
		 * Used for other plugins to provide their bundled assets via filter to
163
		 * prevent the need of storing them in an option or an external api request
164
		 * to w.org.
165
		 *
166
		 * @module photon-cdn
167
		 *
168
		 * @since 6.6.0
169
		 *
170
		 * @param array $assets The assets array for the plugin.
171
		 * @param string $version The version of the plugin being requested.
172
		 */
173
		$assets = apply_filters( "jetpack_cdn_plugin_assets-{$plugin}", null, $version );
174
		if ( is_array( $assets ) ) {
175
			return $assets;
176
		}
177
178
		if ( ! self::is_public_version( $version ) ) {
179
			return false;
180
		}
181
182
		$cache = Jetpack_Options::get_option( 'static_asset_cdn_files', array() );
183
		if ( isset( $cache[ $plugin ][ $version ] ) ) {
184
			if ( is_array( $cache[ $plugin ][ $version ] ) ) {
185
				return $cache[ $plugin ][ $version ];
186
			}
187
			if ( is_numeric( $cache[ $plugin ][ $version ] ) ) {
188
				// Cache an empty result for up to 24h.
189
				if ( intval( $cache[ $plugin ][ $version ] ) + DAY_IN_SECONDS > time() ) {
190
					return array();
191
				}
192
			}
193
		}
194
195
		$url = sprintf( 'http://downloads.wordpress.org/plugin-checksums/%s/%s.json', $plugin, $version );
196
197
		if ( wp_http_supports( array( 'ssl' ) ) ) {
198
			$url = set_url_scheme( $url, 'https' );
199
		}
200
201
		$response = wp_remote_get( $url );
202
203
		$body = trim( wp_remote_retrieve_body( $response ) );
204
		$body = json_decode( $body, true );
205
206
		$return = time();
207
		if ( is_array( $body ) ) {
208
			$return = array_filter( array_keys( $body['files'] ), array( __CLASS__, 'is_js_or_css_file' ) );
209
		}
210
211
		$cache[ $plugin ]             = array();
212
		$cache[ $plugin ][ $version ] = $return;
213
		Jetpack_Options::update_option( 'static_asset_cdn_files', $cache, true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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...
214
215
		return $return;
216
	}
217
218
	/**
219
	 * Checks a path whether it is a JS or CSS file.
220
	 *
221
	 * @param String $path file path.
222
	 * @return Boolean whether the file is a JS or CSS.
223
	 */
224
	public static function is_js_or_css_file( $path ) {
225
		return ( false === strpos( $path, '?' ) ) && in_array( substr( $path, -3 ), array( 'css', '.js' ), true );
226
	}
227
228
	/**
229
	 * Checks whether the version string indicates a production version.
230
	 *
231
	 * @param String  $version the version string.
232
	 * @param Boolean $include_beta_and_rc whether to count beta and RC versions as production.
233
	 * @return Boolean
234
	 */
235
	public static function is_public_version( $version, $include_beta_and_rc = false ) {
236
		if ( preg_match( '/^\d+(\.\d+)+$/', $version ) ) {
237
			// matches `1` `1.2` `1.2.3`.
238
			return true;
239
		} elseif ( $include_beta_and_rc && preg_match( '/^\d+(\.\d+)+(-(beta|rc)\d?)$/i', $version ) ) {
240
			// matches `1.2.3` `1.2.3-beta` `1.2.3-beta1` `1.2.3-rc` `1.2.3-rc2`.
241
			return true;
242
		}
243
		// unrecognized version.
244
		return false;
245
	}
246
}
247
/**
248
 * Allow plugins to short-circuit the Asset CDN, even when the module is on.
249
 *
250
 * @module photon-cdn
251
 *
252
 * @since 6.7.0
253
 *
254
 * @param false bool Should the Asset CDN be blocked? False by default.
255
 */
256
if ( true !== apply_filters( 'jetpack_force_disable_site_accelerator', false ) ) {
257
	Jetpack_Photon_Static_Assets_CDN::go();
258
}
259