Completed
Push — master ( 3c0bb6...7f5b44 )
by Nazar
04:07
created

Assets_processing::css()   C

Complexity

Conditions 8
Paths 1

Size

Total Lines 92
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 41
CRAP Score 8.0064

Importance

Changes 0
Metric Value
cc 8
eloc 50
nc 1
nop 4
dl 0
loc 92
ccs 41
cts 43
cp 0.9535
crap 8.0064
rs 5.538
c 0
b 0
f 0

How to fix   Long Method   

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, JS and HTML files before putting into cache
12
 *
13
 * This is because CSS and HTML files may include other CSS, JS files, images, fonts and so on with absolute and relative paths.
14
 * Methods of this class handle all this assets, applies basic minification to CSS and JS files and produce single resulting file (relative paths to
15
 * files that can't be embedded are converted to absolute). This allows to decrease number of HTTP requests on page and avoid breaking of relative paths for
16
 * fonts, images and other assets after putting them into cache directory as well as minimize contents size by removing comments and other redundant stuff.
17
 */
18
class Assets_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
	];
34
	/**
35
	 * Analyses file for images, fonts and css links and include they content into single resulting css file.
36
	 *
37
	 * Supports next file extensions for possible assets:
38
	 * jpeg, jpe, jpg, gif, png, ttf, ttc, svg, svgz, woff, css
39
	 *
40
	 * @param string   $data                   Content of processed file
41
	 * @param string   $file                   Path to file, that contains specified in previous parameter content
42
	 * @param string   $target_directory_path  Target directory for resulting combined files
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
	public static function css ($data, $file, $target_directory_path = PUBLIC_CACHE, &$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 `.class :disabled` will be handled incorrectly)
91
		 */
92 10
		$data = preg_replace('/\s*:\s+/', ':', $data);
93
		/**
94
		 * Assets processing
95
		 */
96
		// TODO: replace by loop, track duplicated stuff that are subject to inlining and if they appear more than once, don't inline them
97 10
		$data = preg_replace_callback(
98 10
			'/url\((.*)\)|@import\s*(?:url\()?\s*([\'"].*[\'"])\s*\)??(.*);/U',
99
			function ($match) use ($dir, $target_directory_path, &$not_embedded_resources) {
100 10
				$path_matched = @$match[2] ?: $match[1];
101 10
				$path         = trim($path_matched, '\'" ');
102 10
				$link         = explode('?', $path, 2)[0];
103 10
				if (!static::is_relative_path_and_exists($link, $dir)) {
104 4
					return $match[0];
105
				}
106 10
				$extension     = file_extension($link);
107 10
				$absolute_path = static::absolute_path($link, $dir);
108 10
				$content       = file_get_contents($absolute_path);
109 10
				if ($extension == 'css' && @$match[2]) {
110
					/**
111
					 * Only inline CSS imports without media queries, imports with media queries will be placed as separate files
112
					 */
113 6
					if (!trim(@$match[3])) {
114 6
						return static::css($content, $absolute_path, $target_directory_path, $not_embedded_resources);
115
					} else {
116 6
						$filename = static::file_put_contents_with_hash(
117
							$target_directory_path,
118
							$extension,
119 6
							static::css($content, $absolute_path, $target_directory_path)
120
						);
121 6
						return str_replace($path_matched, "'./$filename'", $match[0]);
122
					}
123
				}
124 10
				if (!isset(static::$extension_to_mime[$extension])) {
125
					$filename = static::file_put_contents_with_hash($target_directory_path, $extension, $content);
126
					return str_replace($path_matched, "'./$filename'", $match[0]);
127
				}
128 10
				$filename = md5_file($absolute_path).'.'.$extension;
129 10
				copy($absolute_path, "$target_directory_path/$filename");
130 10
				if (strpos($path, '?') === false) {
131 6
					$not_embedded_resources[] = str_replace(getcwd(), '', "$target_directory_path/$filename");
132
				}
133 10
				return str_replace($path_matched, "'./$filename'", $match[0]);
134 10
			},
135
			$data
136
		);
137 10
		return trim($data);
138
	}
139
	/**
140
	 * Put `$content` into `$dir` where filename is `md5($content)` with specified extension
141
	 *
142
	 * @param string $dir
143
	 * @param string $extension
144
	 * @param string $content
145
	 *
146
	 * @return string Filename (without full path)
147
	 */
148 6
	protected static function file_put_contents_with_hash ($dir, $extension, $content) {
149 6
		$hash = md5($content);
150 6
		file_put_contents("$dir/$hash.$extension", $content, LOCK_EX | FILE_BINARY);
151 6
		return "$hash.$extension";
152
	}
153
	/**
154
	 * Simple and fast JS minification
155
	 *
156
	 * @param string $data
157
	 *
158
	 * @return string
159
	 */
160 10
	public static function js ($data) {
161
		/**
162
		 * Split into array of lines
163
		 */
164 10
		$data = explode("\n", $data);
165
		/**
166
		 * Flag that is `true` when inside comment
167
		 */
168 10
		$in_comment              = false;
169 10
		$continue_after_position = -1;
170 10
		foreach ($data as $index => &$current_line) {
171 10
			if ($continue_after_position >= $index) {
172 6
				continue;
173
			}
174 10
			$next_line = isset($data[$index + 1]) ? trim($data[$index + 1]) : '';
175
			/**
176
			 * Remove starting and trailing spaces
177
			 */
178 10
			$current_line = trim($current_line);
179
			/**
180
			 * Remove single-line comments
181
			 */
182 10
			if (mb_strpos($current_line, '//') === 0) {
183 10
				$current_line = '';
184 10
				continue;
185
			}
186
			/**
187
			 * Starts with multi-line comment
188
			 */
189 10
			if (mb_strpos($current_line, '/*') === 0) {
190 10
				$in_comment = true;
191
			}
192 10
			if (!$in_comment) {
193 10
				$backticks_position = strpos($current_line, '`');
194
				/**
195
				 * Handling template strings can be tricky (since they might be multi-line), so let's fast-forward to the last backticks position and continue
196
				 * from there
197
				 */
198 10
				if ($backticks_position !== false) {
199 6
					$last_item_with_backticks = array_keys(
200
						array_filter(
201
							$data,
202
							function ($d) {
203 6
								return strpos($d, '`') !== false;
204 6
							}
205
						)
206
					);
207 6
					$last_item_with_backticks = array_pop($last_item_with_backticks);
208 6
					if ($last_item_with_backticks > $index) {
209 6
						$continue_after_position = $last_item_with_backticks;
210 6
						continue;
211
					}
212
				}
213
				/**
214
				 * Add new line at the end if only needed
215
				 */
216 10
				if (static::new_line_needed($current_line, $next_line)) {
217 10
					$current_line .= "\n";
218
				}
219
				/**
220
				 * Single-line comment
221
				 */
222 10
				$current_line = preg_replace('#^\s*//[^\'"]+$#', '', $current_line);
223
				/**
224
				 * If we are not sure - just add new line afterwards
225
				 */
226 10
				$current_line = preg_replace('#//.*$#', "\\0\n", $current_line);
227
			} else {
228
				/**
229
				 * End of multi-line comment
230
				 */
231 10
				if (strpos($current_line, '*/') !== false) {
232 10
					$current_line = explode('*/', $current_line)[1];
233 10
					$in_comment   = false;
234
				} else {
235 10
					$current_line = '';
236
				}
237
			}
238
		}
239 10
		$data = implode('', $data);
240 10
		$data = str_replace('</script>', '<\/script>', $data);
241 10
		return trim($data, ';').';';
242
	}
243
	/**
244
	 * @param string $current_line
245
	 * @param string $next_line
246
	 *
247
	 * @return bool
248
	 */
249 10
	protected static function new_line_needed ($current_line, $next_line) {
250
		/**
251
		 * Set of symbols that are safe to be concatenated without new line with anything else
252
		 */
253
		$regexp = /** @lang PhpRegExp */
254 10
			'[:;,.+\-*/{}?><^\'"\[\]=&(]';
255
		return
256 10
			$current_line &&
257 10
			$next_line &&
258 10
			!preg_match("#$regexp\$#", $current_line) &&
259 10
			!preg_match("#^$regexp#", $next_line);
260
	}
261
	/**
262
	 * Analyses file for scripts and styles, combines them into resulting files in order to optimize loading process
263
	 * (files with combined scripts and styles will be created)
264
	 *
265
	 * @param string   $data                   Content of processed file
266
	 * @param string   $file                   Path to file, that contains specified in previous parameter content
267
	 * @param string   $target_directory_path  Target directory for resulting combined files
268
	 * @param bool     $vulcanization          Whether to put combined files separately or to make included assets built-in (vulcanization)
269
	 * @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
270
	 *
271
	 * @return string
272
	 */
273 8
	public static function html ($data, $file, $target_directory_path, $vulcanization, &$not_embedded_resources = []) {
274 8
		static::html_process_links_and_styles($data, $file, $target_directory_path, $vulcanization, $not_embedded_resources);
275 8
		static::html_process_scripts($data, $file, $target_directory_path, $vulcanization, $not_embedded_resources);
276
		// Removing HTML comments (those that are mostly likely comments, to avoid problems)
277 8
		$data = preg_replace_callback(
278 8
			'/^\s*<!--([^>-].*[^-])?-->/Ums',
279 8
			function ($matches) {
280 8
				return mb_strpos('--', $matches[1]) === false ? '' : $matches[0];
281 8
			},
282
			$data
283
		);
284 8
		return preg_replace("/\n+/", "\n", $data);
285
	}
286
	/**
287
	 * @param string   $data                   Content of processed file
288
	 * @param string   $file                   Path to file, that contains specified in previous parameter content
289
	 * @param string   $target_directory_path  Target directory for resulting combined files
290
	 * @param bool     $vulcanization          Whether to put combined files separately or to make included assets 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 8
	protected static function html_process_scripts (&$data, $file, $target_directory_path, $vulcanization, &$not_embedded_resources) {
294 8
		if (!preg_match_all('/<script(.*)<\/script>/Uims', $data, $scripts)) {
295 8
			return;
296
		}
297 8
		$scripts_content    = '';
298 8
		$scripts_to_replace = [];
299 8
		$dir                = dirname($file);
300 8
		foreach ($scripts[1] as $index => $script) {
301 8
			$script = explode('>', $script, 2);
302 8
			if (preg_match('/src\s*=\s*[\'"](.*)[\'"]/Uims', $script[0], $url)) {
303 8
				$url = $url[1];
304 8
				if (!static::is_relative_path_and_exists($url, $dir)) {
305 4
					continue;
306
				}
307 8
				$scripts_to_replace[] = $scripts[0][$index];
308 8
				$scripts_content .= file_get_contents("$dir/$url").";\n";
309
			} else {
310 8
				$scripts_to_replace[] = $scripts[0][$index];
311 8
				$scripts_content .= "$script[1];\n";
312
			}
313
		}
314 8
		$scripts_content = static::js($scripts_content);
315 8
		if (!$scripts_to_replace) {
316 4
			return;
317
		}
318
		// Remove all scripts
319 8
		$data = str_replace($scripts_to_replace, '', $data);
320
		/**
321
		 * If vulcanization is not used - put contents into separate file, and put link to it, otherwise put minified content back
322
		 */
323 8
		if (!$vulcanization) {
324
			// TODO: Remove in 7.x; For backward compatibility, since some modules might use this by specifying file path
325 2
			if (!is_dir($target_directory_path)) {
326
				$target_directory_path = dirname($target_directory_path);
327
			}
328 2
			$filename = static::file_put_contents_with_hash($target_directory_path, 'js', $scripts_content);
329
			// Add script with combined content file to the end
330 2
			$data .= "<script src=\"./$filename\"></script>";
331 2
			$not_embedded_resources[] = str_replace(getcwd(), '', "$target_directory_path/$filename");
332
		} else {
333
			// Add combined content inline script to the end
334 6
			$data .= "<script>$scripts_content</script>";
335
		}
336 8
	}
337
	/**
338
	 * @param string   $data                   Content of processed file
339
	 * @param string   $file                   Path to file, that contains specified in previous parameter content
340
	 * @param string   $target_directory_path  Target directory for resulting combined files
341
	 * @param bool     $vulcanization          Whether to put combined files separately or to make included assets built-in (vulcanization)
342
	 * @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
343
	 */
344 8
	protected static function html_process_links_and_styles (&$data, $file, $target_directory_path, $vulcanization, &$not_embedded_resources) {
345
		// Drop Polymer inclusion, since it is already present
346 8
		$data = str_replace('<link rel="import" href="../polymer/polymer.html">', '', $data);
347 8
		if (!preg_match_all('/<link(.*)>|<style(.*)<\/style>/Uims', $data, $links_and_styles)) {
348 8
			return;
349
		}
350 8
		$dir = dirname($file);
351 8
		foreach ($links_and_styles[1] as $index => $link) {
352
			/**
353
			 * Check for custom styles `is="custom-style"` or styles includes `include=".."` - we'll skip them
354
			 * Or if content is plain CSS
355
			 */
356
			if (
357 8
				preg_match('/^[^>]*(is="custom-style"|include=)[^>]*>/Uim', $links_and_styles[2][$index]) ||
358 8
				mb_strpos($links_and_styles[0][$index], '</style>') > 0
359
			) {
360 8
				$content = explode('>', $links_and_styles[2][$index], 2)[1];
361 8
				$data    = str_replace(
362
					$content,
363 8
					static::css($content, $file, $target_directory_path, $not_embedded_resources),
364
					$data
365
				);
366 8
				continue;
367
			}
368 8
			if (!static::has_relative_href($link, $url, $dir)) {
369 4
				continue;
370
			}
371 8
			$import = preg_match('/rel\s*=\s*[\'"]import[\'"]/Uim', $link);
372
			/**
373
			 * CSS imports are available in Polymer alongside with HTML imports
374
			 */
375 8
			$css_import = $import && preg_match('/type\s*=\s*[\'"]css[\'"]/Uim', $link);
376 8
			$stylesheet = preg_match('/rel\s*=\s*[\'"]stylesheet[\'"]/Uim', $link);
377
			// TODO: Polymer only supports `style[is=custom-style]`, but no `link`-based counterpart, so we can't provide CSP-compatibility for CSS anyway
378 8
			if ($css_import || $stylesheet) {
379
				/**
380
				 * If content is link to CSS file
381
				 */
382 8
				$css  = static::css(
383 8
					file_get_contents("$dir/$url"),
384 8
					"$dir/$url",
385
					$target_directory_path,
386
					$not_embedded_resources
387
				);
388 8
				$data = preg_replace(
389 8
					'/'.$links_and_styles[0][$index].'.*<template>/Uims',
390 8
					"<template><style>$css</style>",
391
					$data
392
				);
393 4
			} elseif ($import) {
394
				/**
395
				 * If content is HTML import
396
				 */
397 4
				$data = str_replace(
398 4
					$links_and_styles[0][$index],
399 4
					static::html(
400 4
						file_get_contents("$dir/$url"),
401 8
						"$dir/$url",
402
						$target_directory_path,
403
						$vulcanization,
404
						$not_embedded_resources
405
					),
406
					$data
407
				);
408
			}
409
		}
410 8
	}
411
	/**
412
	 * @param string $link
413
	 * @param string $url
414
	 * @param string $dir
415
	 *
416
	 * @return bool
417
	 */
418 8
	protected static function has_relative_href ($link, &$url, $dir) {
419
		$result =
420 8
			$link &&
421 8
			preg_match('/href\s*=\s*[\'"](.*)[\'"]/Uims', $link, $url);
422 8
		if ($result && static::is_relative_path_and_exists($url[1], $dir)) {
423 8
			$url = $url[1];
424 8
			return true;
425
		}
426 4
		return false;
427
	}
428
	/**
429
	 * @param string $path
430
	 * @param string $dir
431
	 *
432
	 * @return bool
433
	 */
434 10
	protected static function is_relative_path_and_exists ($path, $dir) {
435 10
		return $dir && !preg_match('#^https?://#i', $path) && file_exists(static::absolute_path($path, $dir));
436
	}
437
	/**
438
	 * @param string $path
439
	 * @param string $dir
440
	 *
441
	 * @return string
442
	 */
443 10
	protected static function absolute_path ($path, $dir) {
444 10
		if (strpos($path, '/') === 0) {
445 6
			return realpath(getcwd().$path);
446
		}
447 10
		return realpath("$dir/$path");
448
	}
449
}
450