Completed
Push — master ( b9e201...9ae2e5 )
by Nazar
04:04
created

Includes_processing::js()   C

Complexity

Conditions 12
Paths 27

Size

Total Lines 70
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 28
CRAP Score 12

Importance

Changes 0
Metric Value
cc 12
eloc 32
nc 27
nop 1
dl 0
loc 70
ccs 28
cts 28
cp 1
crap 12
rs 5.6441
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
 * @package   CleverStyle Framework
4
 * @author    Nazar Mokrynskyi <[email protected]>
5
 * @copyright Copyright (c) 2014-2016, Nazar Mokrynskyi
6
 * @license   MIT License, see license.txt
7
 */
8
namespace cs\Page;
9
10
/**
11
 * Class includes few methods used for processing CSS and HTML files before putting into cache.
12
 *
13
 * This is because CSS and HTML files may contain other includes of other CSS, JS files, images, fonts and so on with absolute and relative paths.
14
 * Methods of this class handles all this includes and put them into single resulting file compressed with gzip.
15
 * This allows to decrease number of HTTP requests on page and avoid breaking of relative paths for fonts, images and other includes
16
 * after putting them into cache directory.
17
 */
18
class Includes_processing {
19
	/**
20
	 * Do not inline files bigger than 4 KiB
21
	 */
22
	const MAX_EMBEDDING_SIZE = 4096;
23
	protected static $extension_to_mime = [
24
		'jpeg' => 'image/jpg',
25
		'jpe'  => 'image/jpg',
26
		'jpg'  => 'image/jpg',
27
		'gif'  => 'image/gif',
28
		'png'  => 'image/png',
29
		'svg'  => 'image/svg+xml',
30
		'svgz' => 'image/svg+xml',
31
		'woff' => 'application/font-woff',
32
		//'woff2' => 'application/font-woff2',
33
		'css'  => 'text/css'
34
	];
35
	/**
36
	 * Analyses file for images, fonts and css links and include they content into single resulting css file.
37
	 *
38
	 * Supports next file extensions for possible includes:
39
	 * jpeg, jpe, jpg, gif, png, ttf, ttc, svg, svgz, woff, eot, css
40
	 *
41
	 * @param string   $data                   Content of processed file
42
	 * @param string   $file                   Path to file, that includes specified in previous parameter content
43
	 * @param string[] $not_embedded_resources Some resources like images and fonts might not be embedded into resulting CSS because of their size
44
	 *
45
	 * @return string    $data
46
	 */
47 10
	static function css ($data, $file, &$not_embedded_resources = []) {
48 10
		$dir = dirname($file);
49
		/**
50
		 * Remove comments, tabs and new lines
51
		 */
52 10
		$data = preg_replace('#(/\*.*?\*/)|\t|\n|\r#s', ' ', $data);
53
		/**
54
		 * Remove unnecessary spaces
55
		 */
56 10
		$data = preg_replace('/\s*([,;>{}(])\s*/', '$1', $data);
57 10
		$data = preg_replace('/\s+/', ' ', $data);
58
		/**
59
		 * Return spaces required in media queries
60
		 */
61 10
		$data = preg_replace('/\s(and|or)\(/', ' $1 (', $data);
62
		/**
63
		 * Duplicated semicolons
64
		 */
65 10
		$data = preg_replace('/;+/m', ';', $data);
66
		/**
67
		 * Minify rgb colors declarations
68
		 */
69 10
		$data = preg_replace_callback(
70 10
			'/rgb\(([0-9,.]+)\)/i',
71
			function ($rgb) {
72 6
				$rgb = explode(',', $rgb[1]);
73
				return
74
					'#'.
75 6
					str_pad(dechex($rgb[0]), 2, 0, STR_PAD_LEFT).
76 6
					str_pad(dechex($rgb[1]), 2, 0, STR_PAD_LEFT).
77 6
					str_pad(dechex($rgb[2]), 2, 0, STR_PAD_LEFT);
78 10
			},
79
			$data
80
		);
81
		/**
82
		 * Minify repeated colors declarations
83
		 */
84 10
		$data = preg_replace('/#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3/i', '#$1$2$3', $data);
85
		/**
86
		 * Remove unnecessary zeros
87
		 */
88 10
		$data = preg_replace('/(\D)0\.(\d+)/i', '$1.$2', $data);
89
		/**
90
		 * Unnecessary spaces around colons (should have whitespace character after, otherwise might be `.c :disabled` and will be handled incorrectly)
91
		 */
92 10
		$data = preg_replace('/\s*:\s+/', ':', $data);
93
		/**
94
		 * Includes processing
95
		 */
96 10
		$data = preg_replace_callback(
97 10
			'/url\((.*?)\)|@import\s*[\'"](.*?)[\'"]\s*;/',
98
			function ($match) use ($dir, &$not_embedded_resources) {
99 10
				$path = @$match[2] ?: $match[1];
100 10
				$path = trim($path, '\'" ');
101 10
				$link = explode('?', $path, 2)[0];
102 10
				if (!static::is_relative_path_and_exists($link, $dir)) {
103 10
					return $match[0];
104
				}
105 10
				$extension = file_extension($link);
106 10
				if ($extension == 'css') {
107
					/**
108
					 * For recursive includes processing, if CSS file includes others CSS files
109
					 * TODO: Support for `@import` with media queries
110
					 */
111 6
					return static::css(file_get_contents("$dir/$link"), "$dir/$link", $not_embedded_resources);
112
				}
113 10
				$content = file_get_contents("$dir/$link");
114 10
				if (!isset(static::$extension_to_mime[$extension]) || filesize("$dir/$link") > static::MAX_EMBEDDING_SIZE) {
115 10
					$path_relatively_to_the_root = str_replace(getcwd(), '', realpath("$dir/$link"));
116 10
					$path_relatively_to_the_root .= '?'.substr(md5($content), 0, 5);
117 10
					if (strpos($path, '?') === false) {
118 6
						$not_embedded_resources[] = $path_relatively_to_the_root;
119
					}
120 10
					return str_replace($path, "'".str_replace("'", "\\'", $path_relatively_to_the_root)."'", $match[0]);
121
				}
122 6
				$mime_type = static::$extension_to_mime[$extension];
123 6
				$content   = base64_encode($content);
124 6
				return str_replace($path, "data:$mime_type;charset=utf-8;base64,$content", $match[0]);
125 10
			},
126
			$data
127
		);
128 10
		return trim($data);
129
	}
130
	/**
131
	 * Simple and fast JS minification
132
	 *
133
	 * @param string $data
134
	 *
135
	 * @return string
136
	 */
137 10
	static function js ($data) {
138
		/**
139
		 * Split into array of lines
140
		 */
141 10
		$data = explode("\n", $data);
142
		/**
143
		 * Flag that is `true` when inside comment
144
		 */
145 10
		$comment = false;
146
		/**
147
		 * Set of symbols that are safe to be concatenated without new line with anything else
148
		 */
149
		$regexp = /** @lang PhpRegExp */
150 10
			'[:;,.+\-*/{}?><^\'"\[\]=&(]';
151 10
		foreach ($data as $index => &$d) {
152 10
			$next_line = isset($data[$index + 1]) ? trim($data[$index + 1]) : '';
153
			/**
154
			 * Remove starting and trailing spaces
155
			 */
156 10
			$d = trim($d);
157
			/**
158
			 * Remove single-line comments
159
			 */
160 10
			if (mb_strpos($d, '//') === 0) {
161 10
				$d = '';
162 10
				continue;
163
			}
164
			/**
165
			 * Starts with multi-line comment
166
			 */
167 10
			if (mb_strpos($d, '/*') === 0) {
168 10
				$comment = true;
169
			}
170
			/**
171
			 * Add new line at the end if only needed
172
			 */
173
			if (
174 10
				$d &&
175 10
				$next_line &&
176 10
				!$comment &&
177 10
				!preg_match("#$regexp\$#", $d) &&
178 10
				!preg_match("#^$regexp#", $next_line)
179
			) {
180 10
				$d .= "\n";
181
			}
182 10
			if ($comment) {
183
				/**
184
				 * End of multi-line comment
185
				 */
186 10
				if (strpos($d, '*/') !== false) {
187 10
					$d       = explode('*/', $d)[1];
188 10
					$comment = false;
189
				} else {
190 10
					$d = '';
191
				}
192
			} else {
193
				/**
194
				 * Single-line comment
195
				 */
196 10
				$d = preg_replace('#^\s*//[^\'"]+$#', '', $d);
197
				/**
198
				 * If we are not sure - just add new like afterwards
199
				 */
200 10
				$d = preg_replace('#//.*$#', "\\0\n", $d);
201
			}
202
		}
203 10
		$data = implode('', $data);
204 10
		$data = str_replace('</script>', '<\/script>', $data);
205 10
		return trim($data, ';').';';
206
	}
207
	/**
208
	 * Analyses file for scripts and styles, combines them into resulting files in order to optimize loading process
209
	 * (files with combined scripts and styles will be created)
210
	 *
211
	 * @param string   $data                   Content of processed file
212
	 * @param string   $file                   Path to file, that includes specified in previous parameter content
213
	 * @param string   $base_target_file_path  Base filename for resulting combined files
214
	 * @param bool     $vulcanization          Whether to put combined files separately or to make includes built-in (vulcanization)
215
	 * @param string[] $not_embedded_resources Resources like images/fonts might not be embedded into resulting CSS because of big size or CSS/JS because of CSP
216
	 *
217
	 * @return string
218
	 */
219 8
	static function html ($data, $file, $base_target_file_path, $vulcanization, &$not_embedded_resources = []) {
220 8
		static::html_process_links_and_styles($data, $file, $base_target_file_path, $vulcanization, $not_embedded_resources);
221 8
		static::html_process_scripts($data, $file, $base_target_file_path, $vulcanization, $not_embedded_resources);
222
		// Removing HTML comments (those that are mostly likely comments, to avoid problems)
223 8
		$data = preg_replace_callback(
224 8
			'/^\s*<!--([^>-].*[^-])?-->/Ums',
225 8
			function ($matches) {
226 8
				return mb_strpos('--', $matches[1]) === false ? '' : $matches[0];
227 8
			},
228
			$data
229
		);
230 8
		return preg_replace("/\n+/", "\n", $data);
231
	}
232
	/**
233
	 * @param string   $data                   Content of processed file
234
	 * @param string   $file                   Path to file, that includes specified in previous parameter content
235
	 * @param string   $base_target_file_path  Base filename for resulting combined files
236
	 * @param bool     $vulcanization          Whether to put combined files separately or to make includes built-in (vulcanization)
237
	 * @param string[] $not_embedded_resources Resources like images/fonts might not be embedded into resulting CSS because of big size or CSS/JS because of CSP
238
	 *
239
	 * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
240
	 */
241 8
	protected static function html_process_scripts (&$data, $file, $base_target_file_path, $vulcanization, &$not_embedded_resources) {
242 8
		if (!preg_match_all('/<script(.*)<\/script>/Uims', $data, $scripts)) {
243 8
			return;
244
		}
245 8
		$scripts_content    = '';
246 8
		$scripts_to_replace = [];
247 8
		$dir                = dirname($file);
248 8
		foreach ($scripts[1] as $index => $script) {
249 8
			$script = explode('>', $script, 2);
250 8
			if (preg_match('/src\s*=\s*[\'"](.*)[\'"]/Uims', $script[0], $url)) {
251 8
				$url = $url[1];
252 8
				if (!static::is_relative_path_and_exists($url, $dir)) {
253 4
					continue;
254
				}
255 8
				$scripts_to_replace[] = $scripts[0][$index];
256 8
				$scripts_content .= file_get_contents("$dir/$url").";\n";
257
			} else {
258 8
				$scripts_to_replace[] = $scripts[0][$index];
259 8
				$scripts_content .= "$script[1];\n";
260
			}
261
		}
262 8
		$scripts_content = static::js($scripts_content);
263 8
		if (!$scripts_to_replace) {
264 4
			return;
265
		}
266
		// Remove all scripts
267 8
		$data = str_replace($scripts_to_replace, '', $data);
268
		/**
269
		 * If vulcanization is not used - put contents into separate file, and put link to it, otherwise put minified content back
270
		 */
271 8
		if (!$vulcanization) {
272
			/**
273
			 * md5 to distinguish modifications of the files
274
			 */
275 2
			$content_md5 = substr(md5($scripts_content), 0, 5);
276 2
			file_put_contents("$base_target_file_path.js", $scripts_content, LOCK_EX | FILE_BINARY);
277 2
			$base_target_file_name = basename($base_target_file_path);
278
			// Add script with combined content file to the end
279 2
			$data .= "<script src=\"$base_target_file_name.js?$content_md5\"></script>";
280 2
			$not_embedded_resources[] = "$base_target_file_name.js?$content_md5";
281
		} else {
282
			// Add combined content inline script to the end
283 6
			$data .= "<script>$scripts_content</script>";
284
		}
285 8
	}
286
	/**
287
	 * @param string   $data                   Content of processed file
288
	 * @param string   $file                   Path to file, that includes specified in previous parameter content
289
	 * @param string   $base_target_file_path  Base filename for resulting combined files
290
	 * @param bool     $vulcanization          Whether to put combined files separately or to make includes built-in (vulcanization)
291
	 * @param string[] $not_embedded_resources Resources like images/fonts might not be embedded into resulting CSS because of big size or CSS/JS because of CSP
292
	 *
293
	 * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
294
	 */
295 8
	protected static function html_process_links_and_styles (&$data, $file, $base_target_file_path, $vulcanization, &$not_embedded_resources) {
296
		// Drop Polymer inclusion, since it is already present
297 8
		$data = str_replace('<link rel="import" href="../polymer/polymer.html">', '', $data);
298 8
		if (!preg_match_all('/<link(.*)>|<style(.*)<\/style>/Uims', $data, $links_and_styles)) {
299 8
			return;
300
		}
301 8
		$dir = dirname($file);
302 8
		foreach ($links_and_styles[1] as $index => $link) {
303
			/**
304
			 * Check for custom styles `is="custom-style"` or styles includes `include=".."` - we'll skip them
305
			 * Or if content is plain CSS
306
			 */
307
			if (
308 8
				preg_match('/^[^>]*(is="custom-style"|include=)[^>]*>/Uim', $links_and_styles[2][$index]) ||
309 8
				mb_strpos($links_and_styles[0][$index], '</style>') > 0
310
			) {
311 8
				$content = explode('>', $links_and_styles[2][$index], 2)[1];
312 8
				$data    = str_replace(
313
					$content,
314 8
					static::css($content, $file, $not_embedded_resources),
315
					$data
316
				);
317 8
				continue;
318
			}
319 8
			if (!static::has_relative_href($link, $url, $dir)) {
320 4
				continue;
321
			}
322 8
			$import = preg_match('/rel\s*=\s*[\'"]import[\'"]/Uim', $link);
323
			/**
324
			 * CSS imports are available in Polymer alongside with HTML imports
325
			 */
326 8
			$css_import = $import && preg_match('/type\s*=\s*[\'"]css[\'"]/Uim', $link);
327 8
			$stylesheet = preg_match('/rel\s*=\s*[\'"]stylesheet[\'"]/Uim', $link);
328
			// TODO: Polymer only supports `style[is=custom-style]`, but no `link`-based counterpart, so we can't provide CSP-compatibility for CSS anyway
329 8
			if ($css_import || $stylesheet) {
330
				/**
331
				 * If content is link to CSS file
332
				 */
333 8
				$css  = static::css(
334 8
					file_get_contents("$dir/$url"),
335 8
					"$dir/$url",
336
					$not_embedded_resources
337
				);
338 8
				$data = preg_replace(
339 8
					'/'.$links_and_styles[0][$index].'.*<template>/Uims',
340 8
					"<template><style>$css</style>",
341
					$data
342
				);
343 4
			} elseif ($import) {
344
				/**
345
				 * If content is HTML import
346
				 */
347 4
				$data = str_replace(
348 4
					$links_and_styles[0][$index],
349 4
					static::html(
350 4
						file_get_contents("$dir/$url"),
351 4
						"$dir/$url",
352 8
						"$base_target_file_path-".basename($url, '.html'),
353
						$vulcanization,
354
						$not_embedded_resources
355
					),
356
					$data
357
				);
358
			}
359
		}
360 8
	}
361
	/**
362
	 * @param string $link
363
	 * @param string $url
364
	 * @param string $dir
365
	 *
366
	 * @return bool
367
	 */
368 8
	protected static function has_relative_href ($link, &$url, $dir) {
369
		$result =
370 8
			$link &&
371 8
			preg_match('/href\s*=\s*[\'"](.*)[\'"]/Uims', $link, $url);
372 8
		if ($result && static::is_relative_path_and_exists($url[1], $dir)) {
373 8
			$url = $url[1];
374 8
			return true;
375
		}
376 4
		return false;
377
	}
378
	/**
379
	 * Simple check for http[s], ftp and absolute links
380
	 *
381
	 * @param string $path
382
	 * @param string $dir
383
	 *
384
	 * @return bool
385
	 */
386 10
	protected static function is_relative_path_and_exists ($path, $dir) {
387 10
		return !preg_match('#^(http://|https://|ftp://|/)#i', $path) && file_exists("$dir/$path");
388
	}
389
}
390