Completed
Push — add/asset-cdn ( 2eecce...8a10c5 )
by
unknown
24:41 queued 16:07
created

Asset_CDN::flush_concatenated_scripts()   D

Complexity

Conditions 10
Paths 17

Size

Total Lines 41
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 24
nc 17
nop 1
dl 0
loc 41
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
 * Plugin Name: Asset CDN
4
 * Description: Speed up Javascript and CSS
5
 * Plugin URI: https://github.com/automattic/jetpack
6
 * Author: Automattic
7
 * Author URI: https://automattic.com
8
 * Version: 0.1.0
9
 * Text Domain: asset-cdn
10
 * Domain Path: /languages/
11
 * License: GPLv2 or later
12
 */
13
14
/**
15
 * 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...
16
 * - versioning (combine ver hashes) and cachebusting
17
 * - concat/minify/serve JS too
18
 * - asset inlining for smaller styles?
19
 * - critical CSS support?
20
 * - non-enqueued assets?
21
 */
22
23
class Asset_CDN {
24
	private static $__instance = null;
25
26
	private $cdn_server;
27
	private $concat_style_groups = array();
28
	private $concat_script_groups = array();
29
	private $inject_critical_css = false;
30
31
	/**
32
	 * Singleton implementation
33
	 *
34
	 * @return object
35
	 */
36
	public static function instance() {
37
		if ( ! is_a( self::$__instance, 'Asset_CDN' ) ) {
38
			self::$__instance = new Asset_CDN();
39
		}
40
41
		return self::$__instance;
42
	}
43
44
	public static function reset() {
45
		self::$__instance = null;
46
	}
47
48
	private function __construct() {
49
		$this->cdn_server = apply_filters( 'jetpack_asset_cdn_url', 'https://cdn.wpvm.io' );
50
		// $this->cdn_server = 'http://localhost:8090';
51
52
		// allow smaller CSS by only minifying assets on the page
53
		add_filter( 'jetpack_implode_frontend_css', '__return_false' );
54
55
		// rewrite CSS tags
56
		add_filter( 'script_loader_tag', array( $this, 'register_concat_scripts' ), -100, 3 );
57
		add_filter( 'style_loader_tag', array( $this, 'register_concat_styles' ), -100, 4 );
58
59
		add_action( 'wp_head', array( $this, 'render_concatenated_styles_head' ), PHP_INT_MAX );
60
		add_action( 'wp_head', array( $this, 'render_concatenated_scripts_head' ), PHP_INT_MAX );
61
		add_action( 'wp_footer', array( $this, 'render_concatenated_styles_footer' ), PHP_INT_MAX );
62
		add_action( 'wp_footer', array( $this, 'render_concatenated_scripts_footer' ), PHP_INT_MAX );
63
	}
64
65
	/**
66
	 * Render functions
67
	 */
68
69
	function render_concatenated_styles_head() {
70
		if ( isset( $this->concat_style_groups[0] ) ) {
71
			$this->render_concatenated_styles( $this->concat_style_groups[0] );
72
		}
73
	}
74
75
	function render_concatenated_styles_footer() {
76
		if ( isset( $this->concat_style_groups[1] ) ) {
77
			$this->render_concatenated_styles( $this->concat_style_groups[1] );
78
		}
79
	}
80
81
	private function render_concatenated_styles( $style_groups ) {
82
		// special URL to concatenation service
83
		global $wp_styles;
84
		$site_url = site_url();
85
		foreach( $style_groups as $media => $styles ) {
86
			$urls = array();
87
			$vers = array();
88
89
			foreach( $styles as $style ) {
90
				$urls[] = str_replace( untrailingslashit( $site_url ), '', $style->src );
91
				$vers[] = $style->ver ? $style->ver : $wp_styles->default_version;
92
			}
93
94
			$cdn_url = $this->cdn_server . '/css?b=' .
95
				urlencode( $site_url ) . '&' .
96
				http_build_query( array( 'f' => $urls ) ) . '&' .
97
				http_build_query( array( 'v' => $vers ) );
98
			// if we are injecting critical CSS, load the full CSS async
99
100
			if ( $this->inject_critical_css ) {
101
				echo '<link rel="preload" onload="this.rel=\'stylesheet\'" as="style" type="text/css" media="' . $media . '" href="' . esc_attr( $cdn_url ) . '"/>';
102
			} else {
103
				echo '<link rel="stylesheet" type="text/css" media="' . $media . '" href="' . esc_attr( $cdn_url ) . '"/>';
104
			}
105
		}
106
	}
107
108
	function render_concatenated_scripts_head() {
109
		$this->flush_concatenated_scripts( 0 );
110
	}
111
112
	function render_concatenated_scripts_footer() {
113
		$this->flush_concatenated_scripts( 1 );
114
	}
115
116
	private function flush_concatenated_scripts( $group ) {
117
		if ( ! isset( $this->concat_script_groups[ $group ] ) ) {
118
			return;
119
		}
120
121
		$scripts = $this->concat_script_groups[ $group ];
122
123
		if ( empty( $scripts ) ) {
124
			return;
125
		}
126
127
		// special URL to concatenation service
128
		global $wp_scripts;
129
		$site_url = site_url();
130
		$urls = array();
131
		$vers = array();
132
133
		foreach( $scripts as $script ) {
134
			$urls[] = str_replace( untrailingslashit( $site_url ), '', $script->src );
135
			$vers[] = $script->ver ? $script->ver : $wp_scripts->default_version;
136
			if ( isset( $script->extra['before'] ) && $script->extra['before'] ) {
137
				echo sprintf( "<script type='text/javascript'>\n%s\n</script>\n", $script->extra['before'] );
138
			}
139
		}
140
141
		$cdn_url = $this->cdn_server . '/js?b=' .
142
			urlencode( $site_url ) . '&' .
143
			http_build_query( array( 'f' => $urls ) ) . '&' .
144
			http_build_query( array( 'v' => $vers ) );
145
146
		// TODO: if there is NO inline or external script tags in the body, render async (maybe?)
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
147
		echo '<script type="text/javascript" src="' . esc_attr( $cdn_url ) . '"></script>';
148
149
		foreach( $scripts as $script ) {
150
			if ( isset( $script->extra['after'] ) && $script->extra['after'] ) {
151
				echo sprintf( "<script type='text/javascript'>\n%s\n</script>\n", $script->extra['after'] );
152
			}
153
		}
154
155
		$this->concat_script_groups[ $group ] = array();
156
	}
157
158
	/**
159
	 * Asset modification functions
160
	 */
161
162
	/**
163
	 * Scripts
164
	 */
165
166
	public function register_concat_scripts( $tag, $handle, $src ) {
167
		global $wp_scripts;
168
169
		// don't do admin for now
170
		if ( is_admin() || ! isset( $wp_scripts->registered[$handle] ) ) {
171
			return $tag;
172
		}
173
174
		$script = $wp_scripts->registered[$handle];
175
176
		if ( $this->should_concat_script( $script ) ) {
177
			$this->buffer_script( $script );
178
			return '';
179
		}
180
181
		// if this is a non-CDN script, and there are existing CDN scripts in this group, print them and reset the
182
		// array
183
		$group = isset( $script->extra['group'] ) ? $script->extra['group'] : 0;
184
		$this->flush_concatenated_scripts( $group );
185
186
		return $tag;
187
	}
188
189 View Code Duplication
	private function should_concat_script( $script ) {
190
		// only concat local scripts
191
		$is_local       = $this->is_local_url( $script->src );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 7 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
192
		// don't concat conditional scripts
193
		$is_conditional = isset( $script->extra['conditional'] );
194
		return apply_filters( 'jetpack_perf_concat_script', $is_local && ! $is_conditional, $script->handle, $script->src );
195
	}
196
197
	private function buffer_script( $script ) {
198
		$group = isset( $script->extra['group'] ) ? $script->extra['group'] : 0;
199
		if ( ! isset( $this->concat_script_groups[$group] ) ) {
200
			$this->concat_script_groups[$group] = array();
201
		}
202
		$this->concat_script_groups[$group][] = $script;
203
	}
204
205
	/**
206
	 * Styles
207
	 */
208
209
	public function register_concat_styles( $tag, $handle, $href, $media ) {
210
		global $wp_styles;
211
212
		// don't do admin for now
213
		if ( is_admin() || ! isset( $wp_styles->registered[$handle] ) ) {
214
			return $tag;
215
		}
216
217
		$style = $wp_styles->registered[$handle];
218
219
		if ( $this->should_concat_style( $style ) ) {
220
			$this->buffer_style( $style );
221
			return '';
222
		}
223
224
		return $tag;
225
	}
226
227
	private function buffer_style( $style ) {
228
		$group = isset( $style->extra['group'] ) ? $style->extra['group'] : 0;
229
		$media = $style->args;
230
		if ( ! $media ) {
231
			$media = 'all';
232
		}
233
		if ( ! isset( $this->concat_style_groups[$group] ) ) {
234
			$this->concat_style_groups[$group] = array();
235
		}
236
		if ( ! isset( $this->concat_style_groups[$group][$media] ) ) {
237
			$this->concat_style_groups[$group][$media] = array();
238
		}
239
		$this->concat_style_groups[$group][$media][] = $style;
240
	}
241
242 View Code Duplication
	private function should_concat_style( $style ) {
243
		// only concat local styles
244
		$is_local       = $this->is_local_url( $style->src );
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 7 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
245
		// don't concat conditional styles
246
		$is_conditional = isset( $style->extra['conditional'] );
247
		return apply_filters( 'jetpack_perf_concat_style', $is_local && ! $is_conditional, $style->handle, $style->src );
248
	}
249
250
	private function is_local_url( $url ) {
251
		$site_url = site_url();
252
		return ( strncmp( $url, '/', 1 ) === 0 && strncmp( $url, '//', 2 ) !== 0 )
253
			|| strpos( $url, $site_url ) === 0;
254
	}
255
}