Completed
Push — add/asset-cdn ( 3084e4...3a5f88 )
by
unknown
08:38
created

Jetpack_Asset_CDN::flush_concatenated_styles()   D

Complexity

Conditions 10
Paths 21

Size

Total Lines 44
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 26
nc 21
nop 1
dl 0
loc 44
rs 4.8196
c 0
b 0
f 0

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
/**
4
 * TODO
0 ignored issues
show
Coding Style introduced by
Comment refers to a TODO task

This check looks TODO comments that have been left in the code.

``TODO``s show that something is left unfinished and should be attended to.

Loading history...
5
 * - asset inlining for smaller styles?
6
 * - critical CSS support?
7
 * - non-enqueued assets?
8
 */
9
10
class Jetpack_Asset_CDN {
11
	private static $__instance = null;
12
13
	private $cdn_server;
14
	private $concat_style_groups = array();
15
	private $concat_script_groups = array();
16
	private $inject_critical_css = false;
17
	private $include_external_assets = false;
18
	private $max_assets_per_tag = 1;
0 ignored issues
show
Unused Code introduced by
The property $max_assets_per_tag is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
19
20
	/**
21
	 * Singleton implementation
22
	 *
23
	 * @return object
24
	 */
25
	public static function instance() {
26
		if ( ! is_a( self::$__instance, 'Jetpack_Asset_CDN' ) ) {
27
			self::$__instance = new Jetpack_Asset_CDN();
28
		}
29
30
		return self::$__instance;
31
	}
32
33
	public static function reset() {
34
		if ( null === self::$__instance ) {
35
			return;
36
		}
37
38
		// allow smaller CSS by only minifying assets on the page
39
		remove_filter( 'jetpack_implode_frontend_css', '__return_false' );
40
41
		// concatenate selected CSS and JS tags
42
		remove_filter( 'script_loader_tag', array( self::$__instance, 'register_concat_scripts' ), -100 );
43
		remove_filter( 'style_loader_tag', array( self::$__instance, 'register_concat_styles' ), -100 );
44
45
		// render buffered assets
46
		remove_action( 'wp_head', array( self::$__instance, 'render_concatenated_styles_head' ), PHP_INT_MAX );
47
		remove_action( 'wp_head', array( self::$__instance, 'render_concatenated_scripts_head' ), PHP_INT_MAX );
48
		remove_action( 'wp_footer', array( self::$__instance, 'render_concatenated_styles_footer' ), PHP_INT_MAX );
49
		remove_action( 'wp_footer', array( self::$__instance, 'render_concatenated_scripts_footer' ), PHP_INT_MAX );
50
51
		self::$__instance = null;
52
	}
53
54
	private function __construct() {
55
		$this->cdn_server = apply_filters( 'jetpack_asset_cdn_url', 'https://cdn.wpvm.io' );
56
		$this->include_external_assets = apply_filters( 'jetpack_asset_cdn_external_assets', false );
57
58
		// allow smaller CSS by only minifying assets on the page
59
		add_filter( 'jetpack_implode_frontend_css', '__return_false' );
60
61
		// concatenate selected CSS and JS tags
62
		add_filter( 'script_loader_tag', array( $this, 'register_concat_scripts' ), -100, 3 );
63
		add_filter( 'style_loader_tag', array( $this, 'register_concat_styles' ), -100, 4 );
64
65
		// rewrite URLs for selected CSS and JS tags
66
		add_filter( 'script_loader_src', array( $this, 'rewrite_script_src' ), -100, 2 );
67
		add_filter( 'style_loader_src', array( $this, 'rewrite_style_src' ), -100, 2 );
68
69
		// flush remaining un-printed CDN assets
70
		add_action( 'wp_head', array( $this, 'render_concatenated_styles_head' ), PHP_INT_MAX );
71
		add_action( 'wp_head', array( $this, 'render_concatenated_scripts_head' ), PHP_INT_MAX );
72
		add_action( 'wp_footer', array( $this, 'render_concatenated_styles_footer' ), PHP_INT_MAX );
73
		add_action( 'wp_footer', array( $this, 'render_concatenated_scripts_footer' ), PHP_INT_MAX );
74
	}
75
76
	/**
77
	 * Rewrite script or style src optionally, if not being concatenated,
78
	 * so they're still served from the CDN
79
	 */
80
81 View Code Duplication
	function rewrite_script_src( $src, $handle ) {
82
		global $wp_scripts;
83
84
		if ( is_admin() || ! isset( $wp_scripts->registered[$handle] ) ) {
85
			return $src;
86
		}
87
88
		$script = $wp_scripts->registered[$handle];
89
90
		if ( ! $this->should_concat_script( $script ) && $this->should_cdn_script( $script ) ) {
91
			// serve this script from the CDN
92
			$parts = parse_url( $src );
93
			$url = $this->cdn_server . '/js';
94
			$url = add_query_arg( array(
95
				'b' => "{$parts['scheme']}://{$parts['host']}",
96
				'f' => array( $parts['path'] ),
97
				'v' => array( $script->ver )
98
			), $url );
99
			return $url;
100
		}
101
102
		return $src;
103
	}
104
105
	function should_cdn_script( $script ) {
106
		$should_cdn = ( $this->include_external_assets || $this->is_local_url( $script->src ) );
107
		return apply_filters( 'jetpack_perf_cdn_script', $should_cdn, $script->handle, $script->src );
108
	}
109
110 View Code Duplication
	function rewrite_style_src( $src, $handle ) {
111
		global $wp_styles;
112
113
		if ( is_admin() || ! isset( $wp_styles->registered[$handle] ) ) {
114
			return $src;
115
		}
116
117
		$style = $wp_styles->registered[$handle];
118
119
		if ( ! $this->should_concat_style( $style ) && $this->should_cdn_style( $style ) ) {
120
			// serve this style from the CDN
121
			$parts = parse_url( $src );
122
			$url = $this->cdn_server . '/js';
123
			$url = add_query_arg( array(
124
				'b' => "{$parts['scheme']}://{$parts['host']}",
125
				'f' => array( $parts['path'] ),
126
				'v' => array( $style->ver )
127
			), $url );
128
			return $url;
129
		}
130
131
		return $src;
132
	}
133
134
	function should_cdn_style( $style ) {
135
		$should_cdn = ( $this->include_external_assets || $this->is_local_url( $style->src ) );
136
		return apply_filters( 'jetpack_perf_cdn_style', $should_cdn, $style->handle, $style->src );
137
	}
138
139
	/**
140
	 * Render functions
141
	 */
142
143
	function render_concatenated_styles_head() {
144
		$this->flush_concatenated_styles(0);
145
	}
146
147
	function render_concatenated_styles_footer() {
148
		$this->flush_concatenated_styles(0);
149
		$this->flush_concatenated_styles(1);
150
	}
151
152
	private function flush_concatenated_styles( $group ) {
153
		if ( ! isset( $this->concat_style_groups[ $group ] ) ) {
154
			return;
155
		}
156
157
		$style_groups = $this->concat_style_groups[ $group ];
158
159
		if ( empty( $style_groups ) ) {
160
			return;
161
		}
162
163
		// special URL to concatenation service
164
		global $wp_styles;
165
		$site_url = site_url();
166
		foreach( $style_groups as $media => $styles ) {
167
			$urls = array();
168
			$vers = array();
169
170
			foreach( $styles as $style ) {
171
				$urls[] = str_replace( untrailingslashit( $site_url ), '', $style->src );
172
				$vers[] = $style->ver ? $style->ver : $wp_styles->default_version;
173
			}
174
175
			$cdn_url = $this->cdn_server . '/css?b=' .
176
				urlencode( $site_url ) . '&' .
177
				http_build_query( array( 'f' => $urls ) ) . '&' .
178
				http_build_query( array( 'v' => $vers ) );
179
180
			// if we are injecting critical CSS, load the full CSS async
181
			if ( $this->inject_critical_css ) {
182
				echo '<link rel="preload" onload="this.rel=\'stylesheet\'" as="style" type="text/css" media="' . $media . '" href="' . esc_attr( $cdn_url ) . '"/>';
183
			} else {
184
				echo '<link rel="stylesheet" type="text/css" media="' . $media . '" href="' . esc_attr( $cdn_url ) . '"/>';
185
			}
186
187
			foreach( $styles as $style ) {
188
				if ( isset( $style->extra['concat-after'] ) && $style->extra['concat-after'] ) {
189
					printf( "<style id='%s-inline-css' type='text/css'>\n%s\n</style>\n", esc_attr( $style->handle ), implode( "\n", $style->extra['concat-after'] ) );
190
				}
191
			}
192
		}
193
194
		$this->concat_style_groups[ $group ] = array();
195
	}
196
197
	function render_concatenated_scripts_head() {
198
		$this->flush_concatenated_scripts( 0 );
199
	}
200
201
	function render_concatenated_scripts_footer() {
202
		$this->flush_concatenated_scripts( 0 ); // in case of late-enqueud header styles
203
		$this->flush_concatenated_scripts( 1 );
204
	}
205
206
	private function flush_concatenated_scripts( $group ) {
207
		if ( ! isset( $this->concat_script_groups[ $group ] ) ) {
208
			return;
209
		}
210
211
		$scripts = $this->concat_script_groups[ $group ];
212
213
		if ( empty( $scripts ) ) {
214
			return;
215
		}
216
217
		global $wp_scripts;
218
		$site_url = site_url();
219
		$urls = array();
220
		$vers = array();
221
222
		foreach( $scripts as $script ) {
223
			$urls[] = str_replace( untrailingslashit( $site_url ), '', $script->src );
224
			$vers[] = $script->ver ? $script->ver : $wp_scripts->default_version;
225
			if ( isset( $script->extra['before'] ) && $script->extra['before'] ) {
226
				echo sprintf( "<script type='text/javascript'>\n%s\n</script>\n", $script->extra['before'] );
227
			}
228
		}
229
230
		$cdn_url = $this->cdn_server . '/js?b=' .
231
			urlencode( $site_url ) . '&' .
232
			http_build_query( array( 'f' => $urls ) ) . '&' .
233
			http_build_query( array( 'v' => $vers ) );
234
235
		echo '<script type="text/javascript" src="' . esc_attr( $cdn_url ) . '"></script>';
236
237
		foreach( $scripts as $script ) {
238
			if ( isset( $script->extra['after'] ) && $script->extra['after'] ) {
239
				echo sprintf( "<script type='text/javascript'>\n%s\n</script>\n", $script->extra['after'] );
240
			}
241
		}
242
243
		$this->concat_script_groups[ $group ] = array();
244
	}
245
246
	/**
247
	 * Asset modification functions
248
	 */
249
250
	/**
251
	 * Scripts
252
	 */
253
254
	public function register_concat_scripts( $tag, $handle, $src ) {
255
		global $wp_scripts;
256
257
		// don't do admin for now
258
		if ( is_admin() || ! isset( $wp_scripts->registered[$handle] ) ) {
259
			return $tag;
260
		}
261
262
		$script = $wp_scripts->registered[$handle];
263
264
		if ( $this->should_concat_script( $script ) ) {
265
			$this->buffer_script( $script );
266
			return '';
267
		}
268
269
		// we flush buffered scripts when we encounter a tag which
270
		// is not eligible for concatenation, so that ordering is preserved
271
		$group = isset( $script->extra['group'] ) ? $script->extra['group'] : 0;
272
		$this->flush_concatenated_scripts( $group );
273
274
		return $tag;
275
	}
276
277
	private function should_concat_script( $script ) {
278
		$should_concat =
279
			( $this->include_external_assets || $this->is_local_url( $script->src ) )
280
			&& ! isset( $script->extra['conditional'] );
281
		return apply_filters( 'jetpack_perf_concat_script', $should_concat, $script->handle, $script->src );
282
	}
283
284
	private function buffer_script( $script ) {
285
		$group = isset( $script->extra['group'] ) ? $script->extra['group'] : 0;
286
		if ( ! isset( $this->concat_script_groups[$group] ) ) {
287
			$this->concat_script_groups[$group] = array();
288
		}
289
		$this->concat_script_groups[$group][] = $script;
290
	}
291
292
	/**
293
	 * Styles
294
	 */
295
296
	public function register_concat_styles( $tag, $handle, $href, $media ) {
297
		global $wp_styles;
298
299
		// don't do admin for now
300
		if ( is_admin() || ! isset( $wp_styles->registered[$handle] ) ) {
301
			return $tag;
302
		}
303
304
		$style = $wp_styles->registered[$handle];
305
306
		if ( $this->should_concat_style( $style ) ) {
307
			$this->buffer_style( $style );
308
			return '';
309
		}
310
311
		return $tag;
312
	}
313
314
	private function buffer_style( $style ) {
315
		$group = isset( $style->extra['group'] ) ? $style->extra['group'] : 0;
316
		$media = $style->args;
317
318
		// rename the 'after' code so that we can output it separately
319
		if ( isset( $style->extra['after'] ) ) {
320
			$style->extra['concat-after'] = $style->extra['after'];
321
			unset( $style->extra['after'] );
322
		}
323
324
		if ( ! $media ) {
325
			$media = 'all';
326
		}
327
328
		if ( ! isset( $this->concat_style_groups[$group] ) ) {
329
			$this->concat_style_groups[$group] = array();
330
		}
331
332
		if ( ! isset( $this->concat_style_groups[$group][$media] ) ) {
333
			$this->concat_style_groups[$group][$media] = array();
334
		}
335
336
		$this->concat_style_groups[$group][$media][] = $style;
337
	}
338
339
	private function should_concat_style( $style ) {
340
		$should_concat =
341
		( $this->include_external_assets || $this->is_local_url( $style->src ) )
342
		&& ! isset( $style->extra['conditional'] );
343
344
		return apply_filters( 'jetpack_perf_concat_style', $should_concat, $style->handle, $style->src );
345
	}
346
347
	private function is_local_url( $url ) {
348
		$site_url = site_url();
349
		return ( strncmp( $url, '/', 1 ) === 0 && strncmp( $url, '//', 2 ) !== 0 )
350
			|| strpos( $url, $site_url ) === 0;
351
	}
352
}