Completed
Push — master ( 480481...695952 )
by Nazar
05:06
created

Assets_processing::absolute_path()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
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[] $not_embedded_resources Some resources like images and fonts might not be embedded into resulting CSS because of their size
43
	 *
44
	 * @return string    $data
45
	 */
46 10
	public static function css ($data, $file, &$not_embedded_resources = []) {
47 10
		$dir = dirname($file);
48
		/**
49
		 * Remove comments, tabs and new lines
50
		 */
51 10
		$data = preg_replace('#(/\*.*?\*/)|\t|\n|\r#s', ' ', $data);
52
		/**
53
		 * Remove unnecessary spaces
54
		 */
55 10
		$data = preg_replace('/\s*([,;>{}(])\s*/', '$1', $data);
56 10
		$data = preg_replace('/\s+/', ' ', $data);
57
		/**
58
		 * Return spaces required in media queries
59
		 */
60 10
		$data = preg_replace('/\s(and|or)\(/', ' $1 (', $data);
61
		/**
62
		 * Duplicated semicolons
63
		 */
64 10
		$data = preg_replace('/;+/m', ';', $data);
65
		/**
66
		 * Minify rgb colors declarations
67
		 */
68 10
		$data = preg_replace_callback(
69 10
			'/rgb\(([0-9,.]+)\)/i',
70
			function ($rgb) {
71 6
				$rgb = explode(',', $rgb[1]);
72
				return
73
					'#'.
74 6
					str_pad(dechex($rgb[0]), 2, 0, STR_PAD_LEFT).
75 6
					str_pad(dechex($rgb[1]), 2, 0, STR_PAD_LEFT).
76 6
					str_pad(dechex($rgb[2]), 2, 0, STR_PAD_LEFT);
77 10
			},
78
			$data
79
		);
80
		/**
81
		 * Minify repeated colors declarations
82
		 */
83 10
		$data = preg_replace('/#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3/i', '#$1$2$3', $data);
84
		/**
85
		 * Remove unnecessary zeros
86
		 */
87 10
		$data = preg_replace('/(\D)0\.(\d+)/i', '$1.$2', $data);
88
		/**
89
		 * Unnecessary spaces around colons (should have whitespace character after, otherwise might be `.c :disabled` and will be handled incorrectly)
90
		 */
91 10
		$data = preg_replace('/\s*:\s+/', ':', $data);
92
		/**
93
		 * Assets processing
94
		 */
95 10
		$data = preg_replace_callback(
96 10
			'/url\((.*)\)|@import\s*(?:url\()?\s*([\'"].*[\'"])\s*\)??(.*);/U',
97
			function ($match) use ($dir, &$not_embedded_resources) {
98 10
				$path_matched = @$match[2] ?: $match[1];
99 10
				$path         = trim($path_matched, '\'" ');
100 10
				$link         = explode('?', $path, 2)[0];
101 10
				if (!static::is_relative_path_and_exists($link, $dir)) {
102 4
					return $match[0];
103
				}
104 10
				$extension     = file_extension($link);
105 10
				$absolute_path = static::absolute_path($link, $dir);
106
				/**
107
				 * Only process CSS imports without media queries, imports with media queries will just be corrected to absolute paths
108
				 */
109 10
				if ($extension == 'css' && @$match[2] && !trim(@$match[3])) {
110
					/**
111
					 * For recursive stylesheets processing, if CSS file includes others CSS files
112
					 */
113 6
					return static::css(file_get_contents($absolute_path), $absolute_path, $not_embedded_resources);
114
				}
115 10
				$content = file_get_contents($absolute_path);
116 10
				if (!isset(static::$extension_to_mime[$extension]) || filesize($absolute_path) > static::MAX_EMBEDDING_SIZE) {
117 10
					$path_relatively_to_the_root = str_replace(getcwd(), '', $absolute_path);
118 10
					$path_relatively_to_the_root .= '?'.substr(md5($content), 0, 5);
119 10
					if (isset(static::$extension_to_mime[$extension]) && strpos($path, '?') === false) {
120 6
						$not_embedded_resources[] = $path_relatively_to_the_root;
121
					}
122 10
					return str_replace($path_matched, "'".str_replace("'", "\\'", $path_relatively_to_the_root)."'", $match[0]);
123
				}
124 6
				$mime_type = static::$extension_to_mime[$extension];
125 6
				$content   = base64_encode($content);
126 6
				return str_replace($path, "data:$mime_type;charset=utf-8;base64,$content", $match[0]);
127 10
			},
128
			$data
129
		);
130 10
		return trim($data);
131
	}
132
	/**
133
	 * Simple and fast JS minification
134
	 *
135
	 * @param string $data
136
	 *
137
	 * @return string
138
	 */
139 10
	public static function js ($data) {
140
		/**
141
		 * Split into array of lines
142
		 */
143 10
		$data = explode("\n", $data);
144
		/**
145
		 * Flag that is `true` when inside comment
146
		 */
147 10
		$in_comment              = false;
148 10
		$continue_after_position = -1;
149 10
		foreach ($data as $index => &$current_line) {
150 10
			if ($continue_after_position >= $index) {
151 6
				continue;
152
			}
153 10
			$next_line = isset($data[$index + 1]) ? trim($data[$index + 1]) : '';
154
			/**
155
			 * Remove starting and trailing spaces
156
			 */
157 10
			$current_line = trim($current_line);
158
			/**
159
			 * Remove single-line comments
160
			 */
161 10
			if (mb_strpos($current_line, '//') === 0) {
162 10
				$current_line = '';
163 10
				continue;
164
			}
165
			/**
166
			 * Starts with multi-line comment
167
			 */
168 10
			if (mb_strpos($current_line, '/*') === 0) {
169 10
				$in_comment = true;
170
			}
171 10
			if (!$in_comment) {
172 10
				$backticks_position = strpos($current_line, '`');
173
				/**
174
				 * Handling template strings can be tricky (since they might be multi-line), so let's fast-forward to the last backticks position and continue
175
				 * from there
176
				 */
177 10
				if ($backticks_position !== false) {
178 6
					$last_item_with_backticks = array_keys(
179
						array_filter(
180
							$data,
181
							function ($d) {
182 6
								return strpos($d, '`') !== false;
183 6
							}
184
						)
185
					);
186 6
					$last_item_with_backticks = array_pop($last_item_with_backticks);
187 6
					if ($last_item_with_backticks > $index) {
188 6
						$continue_after_position = $last_item_with_backticks;
189 6
						continue;
190
					}
191
				}
192
				/**
193
				 * Add new line at the end if only needed
194
				 */
195 10
				if (static::new_line_needed($current_line, $next_line)) {
196 10
					$current_line .= "\n";
197
				}
198
				/**
199
				 * Single-line comment
200
				 */
201 10
				$current_line = preg_replace('#^\s*//[^\'"]+$#', '', $current_line);
202
				/**
203
				 * If we are not sure - just add new line afterwards
204
				 */
205 10
				$current_line = preg_replace('#//.*$#', "\\0\n", $current_line);
206
			} else {
207
				/**
208
				 * End of multi-line comment
209
				 */
210 10
				if (strpos($current_line, '*/') !== false) {
211 10
					$current_line = explode('*/', $current_line)[1];
212 10
					$in_comment   = false;
213
				} else {
214 10
					$current_line = '';
215
				}
216
			}
217
		}
218 10
		$data = implode('', $data);
219 10
		$data = str_replace('</script>', '<\/script>', $data);
220 10
		return trim($data, ';').';';
221
	}
222
	/**
223
	 * @param string $current_line
224
	 * @param string $next_line
225
	 *
226
	 * @return bool
227
	 */
228 10
	protected static function new_line_needed ($current_line, $next_line) {
229
		/**
230
		 * Set of symbols that are safe to be concatenated without new line with anything else
231
		 */
232
		$regexp = /** @lang PhpRegExp */
233 10
			'[:;,.+\-*/{}?><^\'"\[\]=&(]';
234
		return
235 10
			$current_line &&
236 10
			$next_line &&
237 10
			!preg_match("#$regexp\$#", $current_line) &&
238 10
			!preg_match("#^$regexp#", $next_line);
239
	}
240
	/**
241
	 * Analyses file for scripts and styles, combines them into resulting files in order to optimize loading process
242
	 * (files with combined scripts and styles will be created)
243
	 *
244
	 * @param string   $data                   Content of processed file
245
	 * @param string   $file                   Path to file, that contains specified in previous parameter content
246
	 * @param string   $target_directory_path  Target directory for resulting combined files
247
	 * @param bool     $vulcanization          Whether to put combined files separately or to make included assets built-in (vulcanization)
248
	 * @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
249
	 *
250
	 * @return string
251
	 */
252 8
	public static function html ($data, $file, $target_directory_path, $vulcanization, &$not_embedded_resources = []) {
253 8
		static::html_process_links_and_styles($data, $file, $target_directory_path, $vulcanization, $not_embedded_resources);
254 8
		static::html_process_scripts($data, $file, $target_directory_path, $vulcanization, $not_embedded_resources);
255
		// Removing HTML comments (those that are mostly likely comments, to avoid problems)
256 8
		$data = preg_replace_callback(
257 8
			'/^\s*<!--([^>-].*[^-])?-->/Ums',
258 8
			function ($matches) {
259 8
				return mb_strpos('--', $matches[1]) === false ? '' : $matches[0];
260 8
			},
261
			$data
262
		);
263 8
		return preg_replace("/\n+/", "\n", $data);
264
	}
265
	/**
266
	 * @param string   $data                   Content of processed file
267
	 * @param string   $file                   Path to file, that contains specified in previous parameter content
268
	 * @param string   $target_directory_path  Target directory for resulting combined files
269
	 * @param bool     $vulcanization          Whether to put combined files separately or to make included assets built-in (vulcanization)
270
	 * @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
271
	 */
272 8
	protected static function html_process_scripts (&$data, $file, $target_directory_path, $vulcanization, &$not_embedded_resources) {
273 8
		if (!preg_match_all('/<script(.*)<\/script>/Uims', $data, $scripts)) {
274 8
			return;
275
		}
276 8
		$scripts_content    = '';
277 8
		$scripts_to_replace = [];
278 8
		$dir                = dirname($file);
279 8
		foreach ($scripts[1] as $index => $script) {
280 8
			$script = explode('>', $script, 2);
281 8
			if (preg_match('/src\s*=\s*[\'"](.*)[\'"]/Uims', $script[0], $url)) {
282 8
				$url = $url[1];
283 8
				if (!static::is_relative_path_and_exists($url, $dir)) {
284 4
					continue;
285
				}
286 8
				$scripts_to_replace[] = $scripts[0][$index];
287 8
				$scripts_content .= file_get_contents("$dir/$url").";\n";
288
			} else {
289 8
				$scripts_to_replace[] = $scripts[0][$index];
290 8
				$scripts_content .= "$script[1];\n";
291
			}
292
		}
293 8
		$scripts_content = static::js($scripts_content);
294 8
		if (!$scripts_to_replace) {
295 4
			return;
296
		}
297
		// Remove all scripts
298 8
		$data = str_replace($scripts_to_replace, '', $data);
299
		/**
300
		 * If vulcanization is not used - put contents into separate file, and put link to it, otherwise put minified content back
301
		 */
302 8
		if (!$vulcanization) {
303 2
			$hash = md5($scripts_content);
304
			// TODO: Remove in 7.x; For backward compatibility, since some modules might use this b specifying file path
305 2
			if (!is_dir($target_directory_path)) {
306
				$target_directory_path = dirname($target_directory_path);
307
			}
308 2
			file_put_contents("$target_directory_path/$hash.js", $scripts_content, LOCK_EX | FILE_BINARY);
309
			// Add script with combined content file to the end
310 2
			$data .= "<script src=\"./$hash.js\"></script>";
311 2
			$not_embedded_resources[] = str_replace(getcwd(), '', realpath("$target_directory_path/$hash.js"));
312
		} else {
313
			// Add combined content inline script to the end
314 6
			$data .= "<script>$scripts_content</script>";
315
		}
316 8
	}
317
	/**
318
	 * @param string   $data                   Content of processed file
319
	 * @param string   $file                   Path to file, that contains specified in previous parameter content
320
	 * @param string   $target_directory_path  Target directory for resulting combined files
321
	 * @param bool     $vulcanization          Whether to put combined files separately or to make included assets built-in (vulcanization)
322
	 * @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
323
	 */
324 8
	protected static function html_process_links_and_styles (&$data, $file, $target_directory_path, $vulcanization, &$not_embedded_resources) {
325
		// Drop Polymer inclusion, since it is already present
326 8
		$data = str_replace('<link rel="import" href="../polymer/polymer.html">', '', $data);
327 8
		if (!preg_match_all('/<link(.*)>|<style(.*)<\/style>/Uims', $data, $links_and_styles)) {
328 8
			return;
329
		}
330 8
		$dir = dirname($file);
331 8
		foreach ($links_and_styles[1] as $index => $link) {
332
			/**
333
			 * Check for custom styles `is="custom-style"` or styles includes `include=".."` - we'll skip them
334
			 * Or if content is plain CSS
335
			 */
336
			if (
337 8
				preg_match('/^[^>]*(is="custom-style"|include=)[^>]*>/Uim', $links_and_styles[2][$index]) ||
338 8
				mb_strpos($links_and_styles[0][$index], '</style>') > 0
339
			) {
340 8
				$content = explode('>', $links_and_styles[2][$index], 2)[1];
341 8
				$data    = str_replace(
342
					$content,
343 8
					static::css($content, $file, $not_embedded_resources),
344
					$data
345
				);
346 8
				continue;
347
			}
348 8
			if (!static::has_relative_href($link, $url, $dir)) {
349 4
				continue;
350
			}
351 8
			$import = preg_match('/rel\s*=\s*[\'"]import[\'"]/Uim', $link);
352
			/**
353
			 * CSS imports are available in Polymer alongside with HTML imports
354
			 */
355 8
			$css_import = $import && preg_match('/type\s*=\s*[\'"]css[\'"]/Uim', $link);
356 8
			$stylesheet = preg_match('/rel\s*=\s*[\'"]stylesheet[\'"]/Uim', $link);
357
			// TODO: Polymer only supports `style[is=custom-style]`, but no `link`-based counterpart, so we can't provide CSP-compatibility for CSS anyway
358 8
			if ($css_import || $stylesheet) {
359
				/**
360
				 * If content is link to CSS file
361
				 */
362 8
				$css  = static::css(
363 8
					file_get_contents("$dir/$url"),
364 8
					"$dir/$url",
365
					$not_embedded_resources
366
				);
367 8
				$data = preg_replace(
368 8
					'/'.$links_and_styles[0][$index].'.*<template>/Uims',
369 8
					"<template><style>$css</style>",
370
					$data
371
				);
372 4
			} elseif ($import) {
373
				/**
374
				 * If content is HTML import
375
				 */
376 4
				$data = str_replace(
377 4
					$links_and_styles[0][$index],
378 4
					static::html(
379 4
						file_get_contents("$dir/$url"),
380 8
						"$dir/$url",
381
						$target_directory_path,
382
						$vulcanization,
383
						$not_embedded_resources
384
					),
385
					$data
386
				);
387
			}
388
		}
389 8
	}
390
	/**
391
	 * @param string $link
392
	 * @param string $url
393
	 * @param string $dir
394
	 *
395
	 * @return bool
396
	 */
397 8
	protected static function has_relative_href ($link, &$url, $dir) {
398
		$result =
399 8
			$link &&
400 8
			preg_match('/href\s*=\s*[\'"](.*)[\'"]/Uims', $link, $url);
401 8
		if ($result && static::is_relative_path_and_exists($url[1], $dir)) {
402 8
			$url = $url[1];
403 8
			return true;
404
		}
405 4
		return false;
406
	}
407
	/**
408
	 * @param string $path
409
	 * @param string $dir
410
	 *
411
	 * @return bool
412
	 */
413 10
	protected static function is_relative_path_and_exists ($path, $dir) {
414 10
		return $dir && !preg_match('#^https?://#i', $path) && file_exists(static::absolute_path($path, $dir));
415
	}
416
	/**
417
	 * @param string $path
418
	 * @param string $dir
419
	 *
420
	 * @return string
421
	 */
422 10
	protected static function absolute_path ($path, $dir) {
423 10
		if (strpos($path, '/') === 0) {
424 6
			return realpath(getcwd().$path);
425
		}
426 10
		return realpath("$dir/$path");
427
	}
428
}
429