Completed
Push — add/asset-cdn ( cb98ad...3084e4 )
by
unknown
38:38 queued 29:58
created

Jetpack_Asset_CDN::rewrite_script_src()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 23
Code Lines 15

Duplication

Lines 23
Ratio 100 %

Importance

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